Thursday, February 14, 2013

Default keyword in c#

In this post, I am going to explain about default keyword in c#.

Introduction:

As per MSDN default keyword in C# used to assign the default value of the type. In some situation its comes very handy where we don’t want to create object and directly assign the default value of it.

The basic syntax of default is default(T) where t is any reference type of value type and If T is a value type, whether it will be  a numeric value or struct.

Default Keyword usage:

We can use Default keyword in variety of cases.

Assigning value to nullable Type:


We can use it to assign default value to nullable types like below.
using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main() {
            int? i = default(int);
            Console.WriteLine(i);
        }
    }
}

Here output will be.
image

Default Keyword in switch case:

using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main() {
           IsMatch("Hello");
           IsMatch("Jalpesh");
        }

        static void IsMatch(string matchvalue) {
            switch (matchvalue) {
                case "Jalpesh":
                    Console.WriteLine("Perfect Name");
                    break;
                default:
                    Console.WriteLine("Not written proper name");
                    break;

            }
        }
    }
}

Output of this code will be

image

There are many more example I can write!!. So it’s a really useful keyword. Hope you like it. Stay tuned for more.

Shout it

kick it on DotNetKicks.com
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews