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
Here's a suggestion for implementation, following Robert Wagner's logic, but using a generic approach to reduce duplication:
public static int ParseInt32(this NameValueCollection col, string key)
{
return Parse(col, key, int.Parse);
}
public static double ParseDouble(this NameValueCollection col, string key)
{
return Parse(col, key, double.Parse);
}
private static T Parse(NameValueCollection col, string key, Func parse)
{
string value = col[key];
if (string.IsNullOrEmpty(value))
return default(T);
return parse(value);
}
Truth be told, returning zero for a null or empty string scares me; this could cause problems if some values are legitimately zero. Instead, I would have the methods return nullables (int?
, double?
, etc.), which is a slightly more compact approach than the out-parameter pattern used for the framework TryParse
methods. You could do this:
public static int? ParseInt32(this NameValueCollection col, string key)
{
return Parse(col, key, int.Parse);
}
public static double? ParseDouble(this NameValueCollection col, string key)
{
return Parse(col, key, double.Parse);
}
private static T? Parse(NameValueCollection col, string key, Func parse)
where T : struct
{
string value = col[key];
if (string.IsNullOrEmpty(value))
return default(T?);
return parse(value);
}
But that would still throw an exception for non-null-or-empty strings that aren't numeric. It's better to use TryParse. The built-in Func delegates don't support ref or out parameters, so you'd have to declare your own delegate type, but that is fairly trivial.