Returning Null from a generic method

 

Consider this generic method.

   1: public T Get<T>() { 

   2: //return null

   3: }

   4:  

If you want to return null from a C# generic method, which contains the Type(T) parameter, there are 2 options.

a. Restrict the type parameter T, to be class constraint

   1: public T Get<T>() where T : class;

   2: {

   3:    //return null

   4: }

   5:  

Value types or Nullable Values types are not allowed. Reference types only.

b. Return default(T) which return null if T is a reference type or a Nullable value type

   1: public T Get<T>()

   2: {

   3:   return default(T);

   4: }

   5:  

Anything else will simply return their default values.  Here is summary on both reference and value types….

//If T is a reference type

var retVal = f.Get<String>(); //return null

……….

//If T is a value type – int

var retValInt = f.Get<int>(); //return 0

……….

//If T is a value type – char

var retValChar = f.Get<char>(); //return ”

……….

//If T is a value type – bool

var retValBool = f.Get<Boolean>(); //return false

……….

//If T is a value type – enum

var retValEnum = f.Get<EnumType>(); // For enum types, if there are no enum values specified, then the return value is 0. If there are values, then the first enumeration returns as the default.

……….

//If T is a value type – struct

var retValStruct = f.Get<Bar>(); //Structs, returns the value of the struct

……….

//If T is a Nullable<Int32>

var retNullableInt = f.Get<Int32?>(); //return null

……….

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s