Skip to main content

Static Keyword in c#

What can be static in c#?
Class, fields, methods, properties, operators, events, and constructors. Static keyword cannot be used with indexers, finalizers, or types other than classes.

Static Class:
1.       If a class is declared static it can only contain static members the reason for this is the class cannot be instantiated in short it is sealed.
2.       The instance of every non-static class contains a separate copy of instance class fields while a static class will have an only single copy of the fields.

3.        A static class cannot have a constructor but it can contain static constructor without any access modifiers.   


 public static class Employee
    {
        //Static contructor
        static Employee()
        {

        }
        //Static constructor with access specifiers throws error
        //Access modifiers are not allowed on static construtor
        //A static contructor must be parameterless
        public static Employee(int a)
        {

        }
        //Cannot contain a contructor. thows compile time error
        public Employee(){}
        //Cannot contain a not static variable. thows compile time error
        public string hello;
        //Cannot contain a not static method. thows compile time error
        public void DoSomethingElse() { /*...*/  }
        //Can contain a const variable.
        public const string hello3 = "hello 3";
        //Can contain a static Method.
        public static void DoSomething() { /*...*/ }
        //Can contain a static variable.
        public static string hello1;
    }


Static Constructor:
  1.  A static class can have only static constructor if in case instance constructor is specified it throws a compile-time error.
  2. A static constructor must be parameterless.
  3. Access modifiers are not allowed on a Static constructor.
  4. A static constructor cannot be called directly.
  5. A static constructor is called automatically in one of the two cases

a.       Before the first instance of a class is created
b.      Any static members are referenced.

Static Fields:
  1. Use static keyword (modifier) to declare a field as static. A static field can be used with type (class name) itself instead of the object.
  2. An instance of a class contains a separate copy of each instance fields but there is only one copy for each static field.
  3.  If a static field is initialized with another static field which is not yet declared the result will be undefined.
class Test
{
   static int x = y;
   static int y = 5;

   static void Main()
   {
      Console.WriteLine(Test.x);
      Console.WriteLine(Test.y);

      Test.x = 99;
      Console.WriteLine(Test.x);
   }
}
/*
Output:
    0
    5
    99
*/

Comments