HomeCSharpC# Tips & Tricks #34 – “default” keyword

C# Tips & Tricks #34 – “default” keyword

c#This blog post will explain what is the default keyword in C# and the usecase of the 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.

What is the use of “default” keyword in C# ?

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");

    4 Comments

  1. Joe Enos
    January 24, 2011
    Reply

    #3: The System.Type class does have an IsValueType property, so instead of doing this, a better solution would be:

    if (typeof(T).IsValueType)

  2. January 24, 2011
    Reply

    Hey Joe ,

    Thanks for the info …

  3. Sane
    January 26, 2011
    Reply

    And in addition the third example is wrong. For instance, ‘int?’ is value type (because Nullable is struct), but ‘default(int?)’ will be equal to ‘null’ due to equality comparers in Nullable

  4. Joe Enos
    January 26, 2011
    Reply

    I’ve always thought Nullable was a little strange. I’m sure there’s a good reason for it being a value type, but from what I’ve used of it, it would make a lot more sense if it was a class.

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...