tags:

views:

107

answers:

1

The following doesn't compile

public static T Retrieve<T>(this NameValueCollection collection, String key) where T : Object
{

    if (collection.AllKeys.Contains(key))
    {
        try
        {
            val = (T)Convert.ChangeType((object)collection[key], typeof(T));
        }
        catch { }
    }

    return val;            
}

because the Constraint cannot be the object class. So is there a way to contrain T for anything that can be set to a null?

+14  A: 
where T : class

Your current constraint, where T : Object says "anything which is or inherits from System.Object", which is: everything. All types, including Int32 and String, inherit from System.Object. So constraining on Object would do nothing.

Edit: as usual, Eric shines a light on this in a far more accurate way:

"in C# every type derives from object". Not true! The way to correct this myth is to simply replace "derives from" with "is convertible to", and to ignore pointer types: every non-pointer type in C# is convertible to object.

Rex M
I just tried it and it gives you the four object methods: GetType, GetHashCode, ToString and Equals. Bad day yesterday, bunch of stupid posts, sorry.
Yuriy Faktorovich
It's actually a myth that all types inherit from object: http://blogs.msdn.com/ericlippert/archive/2009/08/06/not-everything-derives-from-object.aspx -- However, your point is well taken. The reason we do not allow a constraint to object is because it is already the case that all type arguments must be convertible to object, so this is a constraint that means nothing, and is therefore probably an error.
Eric Lippert
This will not allow a nullable value type for T though, and he wants "anything that can be set to a `null`".
Pavel Minaev