using “Default” Keyword in C#

Sometimes default keywords comes very handy when working with generic objects. It returns the default value when the object is not initialized. For example, we all know integers are initialized to 0 if not given any value. Characters are Empty when not given any value, objects are null when not assigned any value.

These values are assigned based on default keyword.
Thus if we write :

int x = default(int);//will be assigned to 0

will be same as int x;

In case of Generic object when the type is undefined, we can use default to assign specific value to the object. Let us look at the sample :

public T GetDefault<T>()
     return default(T);

The function returns default value for each individual types sent. Thus

int defx = this.GetDefault<int>(); //will assign 0
char defy = this.GetDefault<char>(); // will assign null('\0')
object defz = this.GetDefault<object>(); // will assign null

Thus we can use default keyword to get the default assignments to the object very easily.

Subscribe To Newsletter For your Daily Development Tips and Tricks  

 Best Tips & Tricks on Microsoft Technology Platform 

Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434