Skip to content

Instantly share code, notes, and snippets.

@javafun
Created June 26, 2014 01:19
Show Gist options
  • Save javafun/997b50be5e2b72574842 to your computer and use it in GitHub Desktop.
Save javafun/997b50be5e2b72574842 to your computer and use it in GitHub Desktop.
public static T GetValue<T>(this NameValueCollection collection, string key)
{
if(collection == null)
{
throw new ArgumentNullException("collection");
}
var value = collection[key];
if(value == null)
{
throw new ArgumentOutOfRangeException("key");
}
var converter = TypeDescriptor.GetConverter(typeof(T));
if(!converter.CanConvertFrom(typeof(string)))
{
throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
}
return (T) converter.ConvertFrom(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment