Static Keyword, Static members, Static Constructor, Static Class in C#

Static members:

If you create any member with static keyword, that member is accessible at class level not instance level. That means even though if you create any number of objects for that class which contains static member, that static member value is not reset to initial value.

 

To explain this consider following example. You have banking application and there some level of interest rates based on the amount, default interest rate is set 4%. But you can change the interest rate at any point of based on amount.

 

class Class1

{

        public static double currInterestRate = 4;

 

        public double TotalAmount(double amount)

        {

            return amount * currInterestRate;

        }

}

 

But, you can change the interst rate at any point of time and that has to follow after that as shown below.

 

//checking static members

 Class1 obj = new Class1();

 Console.WriteLine("For less than 1 Lack default interst rate(4%)");

 Console.WriteLine("For 60,000 total amount: " + obj.TotalAmount(60000));

 Console.WriteLine("For greater than 1 Lack interst rate is 6%");

 Class1.currInterestRate = 6;

 Class1 obj1 = new Class1();

 Console.WriteLine("For 1,50,000 total amount: " + obj1.TotalAmount(150000));

 Console.WriteLine("For 2,50,000 total amount: " + obj1.TotalAmount(250000));

 

 

As shown above for less than 1 lack interest rate 4%(Default) and if amount is greater than 1 lack you changed interest rate to 6%. Now the interest rate is set to 6% and not reset to initial value 4% even though new instance is created because here variable currInterestRate static. In this way the static member’s values cannot reset even you created multiple instances.

 

To discuss more about static keywords http://www.dotnetquestionanswers.com/index.php?topic=538.msg541#msg541

 

Static Constructor:

In general, constructor is used to set the value at the time instance creation. If you assign the value to static members in the normal constructor, the value is reset each time object is created, but you don’t need this. You need to assign value to static members only once irrespective of number instances created.

 

For example you are calling method in your constructor which fetches the user’s data at the time of login and you are using this user information for entire application. You may need to create multiple instances for that class to get the information, but it will call the data base each time you create the object. This is performance issue.

 

To solve these types of problems, you can use static constructor which gets executed only once irrespective of number of instances. To explain this I created one class which has static constructor and in the static constructor I am calling the Add() method which increases the static member value by 1 as shown below.

 

class Class2

{

        static int i = 0;

        static Class2()

        {

            Add();

        }

 

         static void Add()

        {

            i = i + 1;

        }

 

         public int getVal()

        {

            return i;

        }

}

 

I am creating the number of instances for the Class2 and calling the getVal() method as shown below.

 

  Class2 obj = new Class2();

  Class2 obj2 = new Class2();

  Class2 obj3 = new Class2();

  Class2 obj4 = new Class2();

  Console.WriteLine("i value: " + obj.getVal().ToString());

 

Eventhough you created 3 instances, the “i” value is displayed as 1, because static constructor is called only once for entire application irrespective of number of instatnces created.

 

Static Class:

If you don’t want to allow users to create instances for your class, you can create static class. Static class contain only static members and it does not contain non static members. You can create instance by using new keyword.

 

For example, create static class and add some static methods for that(because you can not add non static members to static class).

 

static class Class3

{

       public static void display1()

       {

           Console.WriteLine("static display1() method");

       }

 

       public static void display2()

       {

           Console.WriteLine("static display2() method");

       }

}

 

And try to call this class by creating instance and you will get compile time error as shwon below.

 

Class3 obj = new Class3();//gives compile time error

 

Class3.display1();//No error

Class3.display1();//No error

 

You can access static class members only class level and not instance level. By using the static class you can restrict to create instances.

 

Other than static class, you can restrict users to create instance by adding private constrctor as shwon below.

 

class Class3

{

       private Class3()

       {

       }

 

       public void display1()

       {

           Console.WriteLine("static display1() method");

       }

 

       public void display2()

       {

           Console.WriteLine("static display2() method");

       }

}

 

But creating static class is cleaner solution as compared to adding private constructor.

 

                                                                                                              StaticExample.zip (25.57 kb)