ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

GetValue

Retrieve Querystring,Params or Namevalue Collection with default values

Source

public static T GetValue<T>(this NameValueCollection collection, string key, T defaultValue)
{
    if (collection != null && collection.Count > 0)
    {
        if (!string.IsNullOrEmpty(key) && collection[key] != null)
        {
            var val = collection[key];

            return (T)Convert.ChangeType(val, typeof(T));
        }
    }

    return (T)defaultValue;
}

Example

var CallMethod = Request.QueryString.GetValue("method", string.Empty);

var count = Request.QueryString.GetValue("count", 0);

var view_name = Request.Params.GetValue("view", string.Empty);

var entityID = Request.Params.GetValue<Guid>("UUID", Guid.Empty);

Author: Vishal Sharma

Submitted on: 26 dec 2014

Language: C#

Type: NameValueCollection

Views: 3969