I am trying to write a generic Parse method that converts and returns a strongly typed value from a NamedValueCollection. I tried two methods but both of these methods are goin
Another suggestion for implementation, using a TryParse or Parse method with a generic approach. I wrote this originally to convert strings parsed from a csv file into different types, int, decimal, list, etc.
public static bool TryParse<T>(this string value, out T newValue, T defaultValue = default(T))
where T : struct, IConvertible
{
newValue = defaultValue;
try
{
newValue = (T)Convert.ChangeType(value, typeof(T));
}
catch
{
return false;
}
return true;
}
public static T Parse<T>(this string value)
where T : struct, IConvertible
{
return (T) Convert.ChangeType(value, typeof (T));
}
Here, the try parse method first sets the newValue to the default value, then tries to convert value to type T and return the newValue as type T. If the conversion fails, it returns the default value of T.
The Parse method, simply tries to do the conversion, however if its not fail safe and will throw an exception if the conversion fails.
int value = int.Parse(Request.QueryString["RecordID"]);