What Is Static Method And Instance Method In C#

This question has been asked many times. Here I am going to explain what is a static method and instance method.

This question has been asked many times. Here I am going to explain what is a static method and instance method.

Static Method

The static method is defined with a static keyword as I have defined below. The static method uses class memory rather than an object. Static Method is called by class name. We can call a non-static function in static function by making an object of the class. We can’t use this keyword inside the static function.

Eg.

  1. publicstaticvoidshowUsers() {  
  2.     List < int > lst = new List < int > ();  
  3.     for (inti = 0; i <= 10; i = i + 1) {  
  4.         lst.Add(i);  
  5.     }  
  6. }  

Non-StaticMethod

Non-static method or instance method is defined without static keyword as I have defined below. The non-static method is called by making an object of the class. We can use this keyword inside the static function. The non-static method uses a memory of the object. The non-static method can call a static method by class name.

  1. privatevoidperformOperation() {  
  2.     StringBuilderstringBuilder = newStringBuilder();  
  3.     stringBuilder.Append("My First Value");  
  4.     stringBuilder.Append("\nWe should understand ");  
  5.     stringmySatringValue = stringBuilder.ToString();  
  6.     List < MyClass > last = new List < MyClass > ();  
  7.     last.Add(newMyClass() {  
  8.         Id = 1, Name = "Amit", Address = "Bom"  
  9.     });  
  10.     last.Add(newMyClass() {  
  11.         Id = 2, Name = "Amit", Address = "Bom"  
  12.     });  
  13.     last.Add(newMyClass() {  
  14.         Id = 3, Name = "Amit", Address = "Bom"  
  15.     });  
  16.     List < MyClass > lst1 = new List < MyClass > ();  
  17.     last.Where(x => x.Id == 1).ToList().ForEach(x => lst1.Add(x));  
  18. }  

 

Static Method Vs Non Static Method

Static MethodNon Static Method
1. Static method is defined with the static keyword.1. Non Static Method is defined without static keyword.
2. Static method is called by its class name2. Non Static Method is called by making the object of a class.
3. We can’t use this keyword inside the Static Method3. We can use thiskeyword inside Non Static Method
4. Static Method uses the memory of Class4. Non Static Method uses a memory of an object