Pages

Wednesday, 26 February 2014

Static Constructor in C#.NET with Example

Static Constructor in C#.NET with Example 
 
using System;
namespace ConsoleApplication3
{
    class Sample
    {
        public string param1, param2;
        static Sample()
        {
            Console.WriteLine("Static Constructor");
        }
        public Sample()
        {
            param1 = "Sample";
            param2 = "Instance Constructor";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Here Both Static and instance constructors are invoked for first instance
            Sample obj = new Sample();
            Console.WriteLine(obj.param1 + " " + obj.param2);
            // Here only instance constructor will be invoked
            Sample obj1 = new Sample();
            Console.WriteLine(obj1.param1 + " " + obj1.param2);
            Console.ReadLine();
        }
    }
}

Static Constructor
Sample Instance Constructor
Sample Instance Constructor

No comments:

Post a Comment