Raj Aththanayake's Blog Raj Aththanayake's Blog | Returning Null from a generic method
Home > C#

Returning Null from a generic method

1. October 2011

 

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

 

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

……….

C#

Comments are closed