Static Constructor


  • Static Constructor is used to initialize static Data fields
  • Static Data Fields will have maintained only one instance for any no of objects created to the class
  • To make any member of a class static, use static keyword
  • Static members are not accessible with object rather; we need to access with class name only
  • There can be only one static constructor in the class
  • The static constructor should be without parameters
  • It can only access the static members of the class
  • There should be no access modifiers in static constructor definition
  • If a class is static, then we can’t create object for static class
  • Static constructor will be involved only once i.e., 1st object created for the class from second object onwards static constructor will not be called
Example:-

Class Diagram :-



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CAConstructors
{
    class ClsSample
    {
        int v;
        static int s;
        public ClsSample()
        {
            v = 9;
        }
        static ClsSample()
        {
            s = 9;
        }
        public void Display()
        {
            Console.WriteLine("value of i is    :-  " + v);
            v++;
            Console.WriteLine("value of j is    :-  " + s);
            s++;
        }
    }
    class ClsSConstructor
    {
        static void Main()
        {
            ClsSample Obj1 = new ClsSample();
            Obj1.Display();
            ClsSample Obj2 = new ClsSample();
            Obj2.Display();
            ClsSample Obj3 = new ClsSample();
            Obj3.Display();
            ClsSample Obj4 = new ClsSample();
            Obj4.Display();
            Console.Read();
        }
    }
}



Output :-



  • It’s not possible to Initialize non-static Data Fields, with in the static constructors, it raises compilation error
         static ClsSample( )
        {
                v=100//Not allowed
                 s=100;
        }

  • We can initialize static Data fields with a non-static constructor but they lose their static nature
          public ClsSample( )
         {
               v=100;
               s=100; //Allowed But loses its static nature
          }

  • We can initialize static Data fields in both static and non static constructors but static Data Fields will lose their static nature
        public ClsSample( )
       {
               v=100;
                s=100; //Allowed But lose its static nature
        }
        static ClsSample( )
       {
             s=100; //Allowed
        }

No comments:

Post a Comment