Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraint cannot be special class 'System.Object'

Tags:

c#-2.0

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;
    }
like image 820
David W Avatar asked Jul 13 '12 16:07

David W


1 Answers

Just remove where T : System.Object.

By stating:

where T : System.Object

you're saying that the types T usable in your method Parse must inherit from object.
But, since every object in C# inherits from System.Object you 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 type T to be a reference type, so:

where T: class

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:

T Parse<T>(string val)
{
    return (T)Convert.ChangeType(val,typeof(T));
}
like image 122
digEmAll Avatar answered Jan 04 '23 08:01

digEmAll