All You need to Know about Static

In this post we will discuss all about Static Keyword. Static in general means something which is fixed, singular, stable, steady and unchanged.

In C# Static keyword can be used with following:

  • Variables/Fields
  • Classes
  • Constructors
  • Methods
  • Properties

In this article we will cover each of them one by one. Additionally this article also tackles various misconceptions or questions regarding static which can help you in understanding the concept a bit better.

Static Variables/Fields

If you declare a variable inside a class as static that signifies : The class will have only one copy of this static variable in memory irrespective of the number of instances created. This is the reason why static variables are often called class variables as well. These variables are accessed through Class name & not through class instance.

How static variables are different from Instance variables: Lets see

null

Here you can see that all instance variables have their own values for each instance and they are created separately in memory for each instance. But the static variable is created only once and it shares its value among all instances. Moreover if a change is done to static variable then that change will be reflected for all future operations or access to that variable.

Lets see what this means:

StaticEx.JPG

StaticExRes.JPG

As you can see Static variable value keeps on incrementing by 5 (5 + old value) as and when constructor is called i.e. object is created. But Instance variable value increments by 5 just once for each object. This is because instance variable gets created separately for each variable while Static variable is shared among all objects.

How Static variables are different from Application Variables:

Both Static & application variables are common across all users & sessions, then what makes them different, lets see:

  • Application Variables are also similar to the static variables but these variables are available outside the module/function and its scope is available throughout the application.Static variables are local in scope to their module in which they are defined.
  • Static Variables provide Type Safety whereas application variables do not.
  • Compile time error checks done for Static variables but not for application variables.
  • Application.Lock method will lock all application variables, whereas in case of static variables, each static variable synchronization logic will be independent from other static variables.
  • When Code is migrated from classic ASP to Asp.net it is good to have application variables as classic ASP didnt had support for static variables.

Static Classes

A static class is one which is both abstract and sealed by default. Whenever you create a static class, this class is marked as sealed & abstract in MSIL after compilation. Hence a static class is neither inherited nor instantiated. Various features of static class are listed below:

  • Static class cannot be instantiated
  • Static class cannot be inherited
  • Static class cannot have instance constructor (as it cannot be instantiated). Though it can have a static constructor.
  • Since static class will never have an instance hence it cannot have any non static or instance member like variables, instance properties or instance methods.

What are the scenarios for which one should declare a class as static

Generally utility/helper classes are created as static as these classes hold logic that should remain common across all instances. When you need to declare constants for use on UI (hardcoded strings), we can declare them all at one place in a static class. This way you can access them simply with the class name without creating instance and you are not creating a separate memory space for each of them for each of the instances as well.

How a static class different from singleton pattern

  • A singleton class can have one instance but just one. A static class cannot have an instance nor even one.
  • A singleton class can implement an interface while static class cannot implement an interface.
    • Static class cannot implement interface as Polymorphism/interfaces work through instances while static dont use instances.
  • Static doesn’t support inheritance whereas singleton doesn’t pose any restriction on inheritance, this depends on how you implement singleton pattern.
  • Singleton class object can be passed as parameter to methods while same cannot be done with static class since we cannot create object for static class.

Static Constructor

  • Static Constructor can be created for both instance & static classes.
  • Static constructors are required to initialise static variables/fields. It is also used for performing any logic that needs to executed just once.
  • It is called automatically before the first instance is created or any static members are referenced.
  • Static constructor cannot be overloaded and is always created as parameterless.
    • It is parameter less because it is called internally and not explicitly.
    • User has no control over when static constructor is called/executed.
    • It cannot have any access modifiers as well.

Static Methods

A static method is not associated to an instance but to the class directly. Static method is called from the class level without the need of creating an object. This is the sole reason for Main method being declared as static in console applications. Lets see some more features of Static methods:

  • A static method can be called just using class name without creating any object. Ex: Console.ReadLine(); ReadLine is a static method.
  • A static method can access only static fields of the class
  • A static method can call only other static methods. It can not make a call to any instance method.
  • Interfaces cannot have a static method. Interfaces works on implementation through instances while static methods are not related to instances.

Static Properties

  • Can be declared in both static as well as non static class
  • If using a static property to encapsulate a field then make sure to declare that field as static as well.
  • Used for abstracting global data in programs.
  • Mainly static properties are used in same way as static methods.

————————————————————–Edit 1————————————————————–

As rightly mentioned by Bill Richards in Comments that In . Net. Statics are scoped to an app domain and so it is entirely possible for a single application to have multiple instances of a static type. Statics retain their value per App Domain. If you make a change to a static in one App Domain then that change will not be reflected in same static in other App Domain. Lets see this in action.

StaticAppDomainStaticAppDomainResult

As you can see here that I changed the value of static variable i.e. StaticValue from 10 to 100. But when a new app domain is created the value of static variable got changed to initial value i.e. 5 + 5(from constructor) hence 10. This proves that static value is not retained among app domains.

————————————————————–Edit 2————————————————————–

Another important point mentioned by PasserBy  in comments is “Another addition about statics in .NET. Generic class statics are ‘static’ per each type the class is instantiated with as it compiled for use with that type.”  Static retain its value per type the class is instantiated. I have created a generic class and a static field inside it. Have assigned two different values for this static field using two different types for generic class (int & string) . Lets see this in action.

GenericStaticGenericStaticRes

As you can see here both types of same class have their own copy of static values.

9 thoughts on “All You need to Know about Static

  1. Bill Richards says:

    In . Net. Statics are scoped to an app domain and so it is entirely possible for a single application to have multiple instances of a static type.

    This can cause much confusion.

    Liked by 1 person

  2. PasserBy says:

    Another addition about statics in .NET. Generic class statics are ‘static’ per each type the class is instantiated with as it compiled for use with that type.

    full example:
    public class Program
    {
    public static void Main(string[] args)
    {
    Console.WriteLine(“Hello, world!”);

    MyGeneric.Counter = 1;
    MyGeneric.Counter = 2;
    Console.WriteLine(“{0}, {1}”,MyGeneric.Counter, MyGeneric.Counter);
    }
    }

    public class MyGeneric{
    public static int Counter = 0;
    }

    Liked by 1 person

  3. Alex says:

    I’m no longer positive where you are getting your info, however good topic. I must spend a while studying much more or understanding more. Thanks for great info I used to be on the lookout for this info for my mission.

    Like

  4. Tonia Benjamin says:

    I do consider all the ideas you’ve introduced for your post. They are really convincing and will definitely work. Still, the posts are too brief for newbies. Could you please lengthen them a little from next time? Thank you for the post.

    Like

Leave a comment