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:
- TOP-10 Basic C# Interview Questions and Answers
- TOP-10 C# Questions for Advanced Programmers
- 10 Important C# Interview Questions and Answers
- Most Asked C# Interview Q & A
- C# Interview for Beginners
- TOP-10 Advanced C# Interview Questions and Answers
- Introduction to Functions in C#
- C# Jagged Arrays
- C Sharp Interview Questions for 5 Years Experience
- C Sharp Interview Questions for Testers
- C Sharp Questions for 10 Years Experience
- Iteration Statements in C#
- Exception Handling in C#
- C Sharp Methods
- C# Data Types
- C# Vs. C++
- Regular Expressions in C Sharp
- Defining Nested Methods in C Sharp
- C Sharp Dynamic Data Type
- C Custom Exceptions
- How to Generate Random Numbers with C Sharp
- Pass by Value vs Pass by Reference in C Sharp
- C Sharp Inheritance
- C Sharp LINQ
- C Sharp Static Methods