default keyword in c#

The “Default” keyword in c# can be used in the following scenarios .

The main use of default comes in to picture when used in the generic code.

1. To return Type’s Default Value

The Default returns the type’s default value.

For the Integer , it returns 0 , for Boolean , it returns false and for the reference types , it returns null

int valueI = default(Int32);

bool ValueB = default(Boolean);

string senthil = default(String);

MessageBox.Show(valueI.ToString()) ;// "0"

MessageBox.Show(ValueB.ToString()); // "False"

MessageBox.Show(senthil); // nothings

There is another way to get the default value via the following example.

int ValueI = new int();

Here ValueI will be 0 .


2. The keyword default is used within the switch case block to take the default value if nothing is found .

int i =0 ;

switch (i)

{

     case 1 :

               MessageBox.Show("1");

               break;

     case 2 :

               MessageBox.Show("2");

               break;

     case 3:

               MessageBox.Show("3");

               break;

     default:

               MessageBox.Show("Default");

}


3. To know , if the type is a Reference or  Value type

if (default(T) == null)
    MessageBox.Show("Reference Type");
else
    MessageBox.Show("Value Type");
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

4 Comments

  1. Joe Enos January 24, 2011 Reply
    • Senthil Kumar January 24, 2011 Reply
      • Sane January 26, 2011 Reply
        • Joe Enos January 26, 2011 Reply
  2. default keyword in c# | ProgramInDotnet August 9, 2011 Reply

Leave a Reply


x

Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...