Consider the following routine, which simplifies life for me by building in some default behaviors (e.g. no null values, don’t parse “1,1,1” as a valid number):
public static Double CvtToDouble(Object O)
{
if (O == null) return (Double)0;
if (O == System.DBNull) return (Double)0;
if (O is string) return Double.Parse((String)O,
System.Globalization.NumberStyles.Float);
return (T)O;
}
This routine is then repeated for all the num types. I’d like to save on typing and typos by combining them all into
public static T CvtTo<T>(Object O) : where T : "is one of Int32, Int16 ..."
The usual “where T: struct” constraint isn’t enough here, because of the “return (T)0” statement which is not valid for arbitrary value types. Seems like there ought to be some way to genericize this without bending over backward, but I don’t see it. What am I missing ?
You can’t do it.
Generics in .NET is not templates, they are compiled once and thus has to be legal at compile time, not at invocation time.
Since there is no
where T : numberconstraint, or nowhere T : op_add()constraint, you can’t do this with just generics, you either need overloads or runtime checks to do this.