Returning Null from a generic method

A friend of mine asked me a question on this today. I hope you find this useful.
Consider this generic method….

 public T Get<T>() {
    //return null
    }

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

 public T Get<T>() where T : class;
   {
      //return null
   }

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

public T Get<T>()
   {
    return default(T);
   }

Anything else will simply return their default values. Here is a 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 '\0'

//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