December 20, 2010

Static /Private constructor


Static Constructors
Static Constructor is defined with keyword  static , It gets called only for one time after class
has been loaded .

Uses of static constructors. 
1.)If the class is static it can not be instantiated, In that case to initialize the variables we can
    write the static constructor 




Below is the example of calling static constructor

public static class EXPStaticConstructor
{


static int i;
    // Static constructor:
    static EXPStaticConstructor()
    {
        i = 10;
        System.Console.WriteLine("Initialized i in Static Constructor");
    }

    static void someMethod()
    {

        System.Console.WriteLine("The Some method invoked.");
        System.Console.WriteLine(i);


    }
}
    private class Teststatic
    {
        static void Main()
        {


            EXPStaticConstructor.someMethod();  //Before calling this method the static constructor will be called as We are first time using the class EXPStaticConstructor
 for calling the method 
        }
    }





Private Constructors
Instance constructors are public. If we change the access level of an instance constructor to private or if we haven’t specified any access modifiers at all , it becomes a private constructor
Like methods, default access level of a constructor is private.
It is not possible to inherit a class that has only private constructors.
Uses of private constructors. 
**********************
1. Private constructors are commonly used in classes that contain only static 
members.This helps to prevent the creation of an instance of a class by other classes when there are no instance fields or methods in that class.
2. Private constructors are useful when you want to create an instance of a class within
a member of the same class and not want to instantiate it out side the class.
3. Private constructors are used to create an instance of a class within a member of a nested class of the same class.


Below IS the Example of Calling Private Constructor from the inner class
  class Program
    {
        static void Main(string[] args)
             {
                     outer.Inner i = new outer.Inner();
        }
    }
     class outer
    {
        private outer()
        {
            System.Console.WriteLine("Private");
        }


        public  class Inner
        {
            public Inner()
            {
                new outer();    //calling private constructor of outer class
            }


         


        }
    }




Below is the example for calling Private Constructor withing the method
public class EXPPrivate
{
    static int i;
    private EXPPrivate()
    {

        i = 10;
    }

    public static void Create()
    {
        EXPPrivate obj = new EXPPrivate();    // this creates an object  and calls the private constructor

    }

    static void Main()
    {


        Create();

        System.Console.WriteLine(i);

    }
}

No comments:

Post a Comment