C# Statics

Static keyword is used to access the method or variable without creating instance of the class. Static effectively  means ”associated with a type instead of any one instance of the type”. This keyword can be used in multiple structures. IN this article i’ll focus on static keyword used with methods, classes and variables. First lets take look at variables.

Static Variables

Static variables allows to access the values from other class,if its public, without creating the instance of the object.

In My example use MyClass to store two static fields with initial values. I can acess those variabels from Program Class. I dont need instance of the class to call the variables.

class Program
{
  static void Main(string[] args)
  {
      Console.WriteLine(MyClass.i.ToString()+" "+MyClass.name);
  }
}

class MyClass
{
  public static int i=0;
  public static string name="John";
}

Static  Methods

To call static method we don’t need  an instance of the class—this makes them slightly faster. Static methods can be both public or private.  A static method cannot access non-static class level members. It has no “this” pointer. We can not refer to non-static fields from static method.

This is modified version of previous example. This time I have just one static method in MyClass. I’m calling this method from Program class without creating the instance of an object.

 

class Program
{
  static void Main(string[] args)
  {
      MyClass.Print();
  }

}
class MyClass
{
  public static void Print()
  {
     Console.WriteLine("This is Static method");
  }
}

 

Static Classes

A static class is never instantiated. The static keyword on a class enforces that a type not be created with a constructor. Class with static keyword can not have any instances.This eliminates misuse of the class.

A static class is a class which can only contain static members. Like variables and methods from previous examples.

static class MyClass
// Line below can not be executed. 

// MyClass a = new MyClass();

Now you know the basic implementation of static keyword it can be useful when working with large and complex projects whits a lot of connections. Statics can improve the performance and make variables/methods easier to access. In my Unity Tutorials I’ll demonstrate the use of statics in real word examples. Stay Awesome!