Using the default keyword in C#

The keyword default plays several and important roles in the C# language, therefore, I will enumerate some cases where the default keyword is used.


Introduction:

The keyword default plays several and important roles in the C# language, therefore, I will enumerate some cases where the default keyword is used.

First use case:

The keyword default is used within the switch ... case bloc, to illustrate how, I propose this example:

Color x = new Color();

switch (x)

{

case Color.Red :

    MessageBox.Show("This is not a primary color");

    //TO DO: Perform some task

    break;

case Color.Green :

    MessageBox.Show("This is not a primary color");

    //TO DO: Perform some task

    break;

case Color.Blue:

    MessageBox.Show("This is not a primary color");

    //TO DO: Perform some task

    break;

default:

    MessageBox.Show("This is not a primary color");

}

As you see the default play the role of somewhat the exception catcher or the else keyword within a given condition block, but you tell me OK I know this. Have you any thing new where using the keyword default is necessary. YES of course, here are two other use cases.

Second use case:

Imagine if it is necessary to reset the value of a given generic type, you can employ this code for example:

using System;

using System.Collections.Generic;

using System.Text;

 

public class myType<T>

    {

        public myType() { }

        private T _Attribute1;

        private T _Attribute2;

        public T Attribute1

        {

            get { return _Attribute1; }

            set { _Attribute1 = value; }

        }

        public T Attribute2

        {

            get { return _Attribute1; }

            set { _Attribute2 = value; }

        }

        public T method()

        {

            //TO DO: implement some tasks here else

            return null;

        }

        //To reset the type T defined by the class user

        public void ResetGenericType()

        {

            Attribute1 = default(T);

            Attribute2 = default(T);

        } 

    }

Third use case

Suppose now that you want to know whether a generic type is of reference like a String or of value like an Int.

using System;

using System.Collections.Generic;

using System.Text;

 

public class myType<T>

{

    public myType()

    {

        if (default(T) == null)

            Console.WriteLine("T is a type of reference.");

        else

            Console.WriteLine("T is a type of value.");

       

    }

    //TO DO: Implement the rest of the class members

}

The keyword default is certainly used within other contexts but there is a thing that one should keep in mind is that in fact every keyword within the C# syntax has to be appreciated

God Dotneting!!!