29 October 2013

Static Method in C#

Introduction
The methods in C# may or may not take parameters and they may or may not return a value. Also, a custom method that is also known as a user defined method may be declared non-static (instance level) or static (class level). When a method is static then it can be invoked directly from the class level without creating an object. This is the reason for making a main() function/method static. Another example is the WriteLine() method that is called/used without creating any object. Let's explore further using an example.
    class Program
   
 {
       
 public static void withoutObj()
       
 {
           
 Console.WriteLine("Hello");
       
 }
 
        static void Main()
       
 {
           
 Program. withoutObj();
           
 Console.ReadKey();
       
 }
   
 }
In the above example, I will be calling a method using the class name itself without an object being used for the WriteLine().
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 of those data members. Let's have 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 non-static 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 have 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.
Notable Points here are:

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

No comments:

Post a Comment