Link Search Menu Expand Document

C Sharp Static Methods

In C#, a static method stores just one copy of the method at the Type level rather than the object level. Every instance has a similar copy of the method and its data in the class.

The method’s most recently changed all objects of that Type share value. Static methods are accessed by utilizing the class name rather than the class instance. Static methods are shown via the Console class and its Read and Write methods.

The code sample below invokes Console.WriteLine method without creating an instance of the Console class; you can also use the ReadKey methods.

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

Applying the Static Method

Typically, we declare a set of data members for a class, and each object of that class has a distinct copy of each of those data members.

Here is 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(); 
      } 
  }

As myVar is a non-static field in the above example, we must first build an object of that type to utilize it.

All objects of that class share static data.

There will be just one copy of static data for all objects in a class.

Let’s look at 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(); 
     } 
 }

Since the field is static, we don’t have an object to utilize in the example above.

You can develop your static method if you create your class and believe that only one copy of the data (method) is required among all class instances.

The Following are Noteworthy Points

  • A static method can be called from the class level.
  • A static method does not necessitate the use of a class object.
  • As any main() function is shared throughout the whole class scope, it is always preceded by the term static.

Other useful articles:


Back to top

© , C Sharp Online — All Rights Reserved - Terms of Use - Privacy Policy