Learn about Static Method In C#

Introduction

C# supports two types of class methods: static and nonstatic. Any normal method is a nonstatic method. 

Static Method in C#

A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. The last updated value of the method is shared among all objects of that Type. That means all class instances share the exact copy of the method and its data. 

Static methods are called by using the class name, not the instance of the class. 

The Console class and its Read and Write methods exemplify static methods. The following code example calls Console.WriteLine and Console.ReadKey methods without creating an instance of the Console class. 

class Program  
{  
    public static void withoutObj()  
    {  
        Console.WriteLine("Hello");  
    }  
     static void Main()  
    {  
        Program. withoutObj();  
        Console.ReadKey();  
    }  
}  

Using Static Method

Usually, we define a set of data members for a class, and then every object of that class will have a separate copy of each data member. Let's give an example.

class Program  
  {  
      public int myVar;  //a non-static field  
        static void Main()  
      {  
          Program p1 = new Program();  //a object of class  
          p1.myVar = 10;  
          Console.WriteLine(p1.myVar);  
          Console.ReadKey();  
      }  
  }  

In the above example, myVar is a nonstatic field so to use this field; we first need to create the object of that class. On the other hand, static data is shared among all the objects of that class. That is, for all the objects of a class, there will be only one copy of static data. Let's give an example.

class Program  
 {  
     public static int myVar;  //a static field  
       static void Main()  
     {  
         //Program p1 = new Program();  //a object of class  
         myVar = 10;  
         Console.WriteLine(myVar);  
         Console.ReadKey();  
     }  
 }  

In the above, we don't have an object of the class to use that field since the field is static.

If you create your own class and think only one copy of the data (method) is needed among all instances of the class, you can create your own static method. Learn more here: Static Class  and Static Class Members In C#

Notable Points here are

  1. A static method can be invoked directly from the class level
  2. A static method does not require any class object
  3. Any main() method is shared through the entire class scope, so it always appears with a static keyword.

Conclusion

This article taught us Static Method In C#. C# language also has several other types of methods. Read more Types of Methods in C#.

Thanks for reading.

HAPPY CODING!!


Similar Articles