Static Methods In Classes

Lesson 30
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

Static methods in classes are methods that can be called without creating an instance of the class. These methods are associated with the class rather than with any particular instance of the class.

To create a static method in C#, we use the “static” keyword when declaring the method. Here’s an example:

public class MyClass
{
    public static void MyStaticMethod()
    {
        Console.WriteLine("This is a static method.");
    }
}

In this example, we’ve created a static method called MyStaticMethod in the MyClass class. The method is declared with the static keyword.

To call a static method, we can use the class name followed by the method name:

MyClass.MyStaticMethod();

Note that we don’t need to create an instance of MyClass before calling MyStaticMethod.

Static methods are useful when we want to perform an action that doesn’t depend on any specific instance of the class. For example, if we had a class called MathUtils, we might want to create a static method called Add that could add two numbers together. We wouldn’t need to create an instance of MathUtils to use the Add method – we could just call it directly on the class:

int sum = MathUtils.Add(3, 4);