My function requires you pass it a string and a Type as T. Based on T i want to parse the string val as that type, but I get the error from the title of this question. Anyone that has any insight or other ways of accomplishing this function, I would greatly appreciate it.
T Parse<T>(string val) where T : System.Object
{
TypeCode code = Type.GetTypeCode(typeof(T));
switch (code)
{
case TypeCode.Boolean:
return System.Boolean.Parse(val);
break;
case TypeCode.Int32:
return Int32.Parse(val);
break;
case TypeCode.Double:
return Double.Parse(val);
break;
case TypeCode.String:
return (string)val;
break;
}
return null;
}
Just remove
where T : System.Object.By stating:
you’re saying that the types
Tusable in your methodParsemust inherit from object.But, since every object in C# inherits from
System.Objectyou don’t need that constraint (and probably that’s one of the reasons why the compiler does not allow that).Also, since you’re returning
null, you should constraint the typeTto be a reference type, so:But in this way you can’t return a boolean, integer or whatever value type.
However, your code basically mimics the functionality of
Convert.ChangeType, the only difference is that you’re using generics to return the correct type instead of object, but is basically equal to this: