Dot Net For All

All about the Static Keyword with C#

In this article I will discuss about the static keyword in C# and where it can be used like static variables, static classes, static methods and static constructors.

Lets start with exploring the Static Class in C#.

Static class in C#

Static classes in C# are with the intention of never being instantiated. It contains a group of static data members and static member functions. We can say that the class exist to group a set of related static members together.

Static keyword can only be applied to the reference types i.e. classes and not to the value type(structures) as value type are always created to be instantiated.

Important points for static class in C#

  1. Static classes can be declared using the static keyword while declaring a class itself otherwise it will be a simple class which can be instantiated.
  2. There is no default constructor for static class..
  3. The class is only derived from the System.Object and no other class or interface can be inherited as inheritance is applicable for instance of class as static class cannot be instantiated.
  4. This class cannot be used as field , method parameter or local variable as all of these represent the instance of the class.
  5. Static classes are sealed and abstract in nature.
  6. Using static method has better performance then using the instance method as for static method the CLR emits the call IL instruction. More about this I have covered in one of my article here
  7. System.Math and System.Console are good examples of static classes.

In the end of this article I will show you how to create a static class and its possible use.

Static Constructor

Static constructors are used to initialize the static fields of a class. Static field initializers are executed just before the static constructors are called. If a type has no static constructor, field initializers are executed just before the type being used or it will totally depend on the run time when to execute them. It means that presence of the static constructors allows the static field initializers to run later in the program.

The one point we should note about static initializer is that they are completely thread safe, as the way they work in .NET or C# is that only one thread is there in static initializer and CLR manages it is very efficiently.

Static fields initializers  are executed in the order in which they are declared in class. Static fields can be of any type unlike constants(which I have discussed here.) which can be only primitive type like int, string etc.

    public class MyClass
    {
        public static int myVar = myVar1; // myVar = 0;
        public static int myVar1 = 3; // myVar = 0
    }

But if we swap the execution of both of the code statements of the class above in that case myVar’s value will be initialized to 3.

Static Class Example

In this part of the article I will discuss about an example which I think can be right candidate for a a static class usage. Suppose in my project I want to have a single store for some of the collection so that it is uniform across all of the application, in that case I can declare the class as static. As shown in the below code snippet I want to maintain a collection of Person class across my project and I should be able to add or retrieve the data from the collection. Please note that this example is not thread safe. More about thread safety you can read here.

   public class Person
    {
        public string Name { get; set; }     
    }

    public static class PersonCollection
    {
        private static IList<Person> personList = new List<Person>();

        static PersonCollection()
        {
            personList = PopulatePerson();
        }

        private static IList<Person> PopulatePerson()
        {
            //Populate from DataSource
            return new List<Person>();
        }

        public static Person GetPerson(Person p)
        {
            if(personList.Where(item => item.Name.Equals(p.Name)).Count() > 0)
            {
                return personList.Where(item => item.Name.Equals(p.Name)).ElementAt(0);
            }
            return null;
        }

        public static void AddPerson(Person p)
        {
            personList.Add(p);
            AddToSource(p);
        }

        private static void AddToSource(Person p)
        {
            //update the newly added person to daatsource
        }
    }

In this article I have discussed about the static keyword and various usage of the static keyword with class and constructors as well as with the fields.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview