Unknown Generic Type cannot be NULL and default(T)

Lets say we are creating a generic method of type T used to convert one type into another. That being said there might be a type conversion exception thrown within the method, if this happens we want to simply return a null indicating that the conversion did not happen correctly. Unfortunately, generic types cannot be set to null, this is because a generic type could be a reference type or a value type depending on what is passed in. Because of this possibility and the fact that value types cannot be implicitly converted to null you must use a new ‘default’ keyword which checks the passed in type to see if it evaluates to a reference type or a value type, if a reference type the passed in type is set to null, if a value type it is set to the default value for that value type.

8 internal static T Cast(object o)

9 {

10 T value;


12 try

13 {

14 value = (T) o;

15 }

16 catch

17 {

18 value = default(T);

19 }


21 return value;

22 }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s