A static method in C# is a method that belongs to the class rather than a specific instance. It can be called directly using the class name without creating an object and is often used for class-level operations.
The syntax for defining a static method in C# is as follows:
access_specifier static return_type MethodName(parameters) { // Method body }
- access_specifier: It specifies the visibility level of the method (e.g., public, private, etc).
- static: This keyword indicates that the method is static.
- return_type: It represents the data type of the value the method returns. For methods that do not return any value, the return type is void.
- MethodName: This is the name of the method.
- parameters: These are the input values passed to the method (if any).
- Method body: This is the block of code inside the method that defines its functionality.
Here are the key features of static methods in C#:
- No Instance Required: Static methods can be called directly using the class name, without creating an object.
- Limited Access: Static methods can only access other static members of the class, not instance-specific ones.
- Main Method: The Main method, the entry point of a C# application, is always declared as static.
Here is source code of the C# Program to Implement Static Method. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Implement Static Method */ using System; class Program { static void stamethod() { Console.WriteLine("Static Method"); } void MethodB() { Console.WriteLine("Instance Method"); } static char stamethod2() { Console.WriteLine("Static Method"); return 'C'; } static void Main() { Program.stamethod(); Console.WriteLine(Program.stamethod2()); Program programInstance = new Program(); programInstance.MethodB(); Console.Read(); } }
1. This C# program showcases the implementation of static methods.
2. Two static methods are created, and they do not require instances of the class to be called.
3. Static methods are called using the type name, not an instance identifier.
Static Method Static Method C Instance Method
- Simplicity: No need to create object instances, making them easy to use.
- Memory Efficiency: Static methods do not consume memory per instance, saving memory.
- Code Reusability: They can be called from anywhere, promoting code reuse and reducing duplication.
- Predictable Behavior: No reliance on object state, leading to more consistent and predictable results.
- Global Access: Static methods are accessible globally, without requiring references or object creation.
Sanfoundry Global Education & Learning Series – 1000 C# Programs.
- Practice MCA MCQs
- Apply for Computer Science Internship
- Check C# Books
- Practice Computer Science MCQs
- Check MCA Books