add a static method to a class in csharp

To add a static method to a class in C#, you can simply prefix the method definition with the keyword static and the access modifier of your choice. Here's an example:

main.cs
public class MyClass
{
    public static void MyStaticMethod()
    {
        // Method logic goes here
    }
}
111 chars
8 lines

In the example above, a new static method called MyStaticMethod is added to the MyClass class. Since the method is declared as static, it can be accessed directly via the class itself, rather than an instance of the class.

To call the static method, you can simply use the class name followed by the method name:

main.cs
MyClass.MyStaticMethod();
26 chars
2 lines

This will call the static method directly, without requiring an instance of the MyClass class.

related categories

gistlibby LogSnag