Wednesday, March 8, 2017

Various use of default keyword

First Use

default keyowrd used in switch cases, which is known to everyone.
It can be used as below

Color x = new Color();
switch (x)
case Color.Black :
    MessageBox.Show("This is BLACK color"); 
case Color.White :
    MessageBox.Show("This is WHITE color");
    MessageBox.Show("This is not a valid color");

Second Use

While using generic classes, we face one issue to the assignment of parameterized type T.
In case of generic you do know that the type of T whether is it value type, or reference type
so how will you assign type T , null or zero. Because null is invalid for integer and 0 is invalid for string.
See example below

  private static void Swap(ref T a, ref T b) 
            //T temp = null; // Is valid for reference type only
           // T temp = 0;// can't assign int to type T
              T temp = default(T);

            temp = a;
            a = b;
            b = temp;                        

class Program
        static void Main(string[] args)
            string First = "a";
            string second = "b";

            Swap(ref First, ref second);

            int FirstNum = 2;
            int secondNum = 6;

            Swap(ref FirstNum, ref secondNum);

Third Use

default keyword used to know the default value of primitive types
See Example below

Console.WriteLine($"default value of int is {default(int)}");
Console.WriteLine($"default value of bool is {default(bool)}");
Console.WriteLine($"default value of string is {default(string)}");

Fourth Use

default keyword can be in assigning default values to a structure variable. When we we strucutre there is mandate to
new its object. So in that case we can use default keyword instead of creatign an object of structure using new keyword.
Suppose we have stutterer like this

 struct Article
        public String url;
        public String title;        
        public int pages;

class Program
        static void Main(string[] args)
            Article obj = default(Article);

            obj.pages = 10;
            obj.title = "ADS";
            obj.url = "";


In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T.

When you do not know the following in advance:
Whether T will be a reference type or a value type.
If T is a value type, whether it will be a numeric value or a struct.

Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types.

For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.