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.
- publicstaticvoidshowUsers() {
- List < int > lst = new List < int > ();
- for (inti = 0; i <= 10; i = i + 1) {
- lst.Add(i);
- }
- }
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.
- privatevoidperformOperation() {
- StringBuilderstringBuilder = newStringBuilder();
- stringBuilder.Append("My First Value");
- stringBuilder.Append("\nWe should understand ");
- stringmySatringValue = stringBuilder.ToString();
- List < MyClass > last = new List < MyClass > ();
- last.Add(newMyClass() {
- Id = 1, Name = "Amit", Address = "Bom"
- });
- last.Add(newMyClass() {
- Id = 2, Name = "Amit", Address = "Bom"
- });
- last.Add(newMyClass() {
- Id = 3, Name = "Amit", Address = "Bom"
- });
- List < MyClass > lst1 = new List < MyClass > ();
- last.Where(x => x.Id == 1).ToList().ForEach(x => lst1.Add(x));
- }
Static Method Vs Non Static Method
Static Method | Non 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 name | 2. Non Static Method is called by making the object of a class. |
3. We can’t use this keyword inside the Static Method | 3. We can use thiskeyword inside Non Static Method |
4. Static Method uses the memory of Class | 4. Non Static Method uses a memory of an object |