Published on

Static methods in C#

Authors
  • avatar
    Name
    Cristian Pique
    LinkedIn

Introduction

Static methods in C# are methods that belong to a class rather than an instance of a class. They can be called on the class itself, rather than on an instance of the class. This means that they do not have access to the instance variables of the class, and they cannot be overridden by subclasses.

A static method is defined by using the "static" keyword before the return type, and it can only access static members of the class. The signature of a static method includes the "static" keyword, the return type, the name of the method, and its parameters.

Here is an example of a static method in C#:

class MyClass {
    static int addNumbers(int a, int b) {
        return a + b;
    }
}

Static methods are useful for utility functions or functions that don't depend on the state of an object. For example, a Math class can have a static method that calculates the square root of a number.

class Math {
    static double squareRoot(double number) {
        return Math.Sqrt(number);
    }
}

Static methods can also be used to create factory methods, which are methods that create and return objects of a certain type.

class MyFactory {
    static MyClass createMyClass() {
        return new MyClass();
    }
}

Pros & cons

It is important to use static methods with caution, as they can make the code harder to test and maintain. Since they don't have access to the instance variables of a class, they can make the code more tightly coupled and harder to change. Also, they can make the code harder to test, since you cannot mock or stub them.

Advantages of static methods are that they don't need an instance of the class to be called, and they don't consume memory for each object. Disadvantages are that they can make the code harder to test and maintain, and they can make the code more tightly coupled.

To create a static method in C#, we need to use the "static" keyword before the return type of the method and make sure that the method only accesses static members of the class.

Summary

In conclusion, static methods in C# are methods that belong to a class rather than an instance of a class. They can be useful for utility functions or factory methods, but they can also make the code harder to test and maintain. It is important to use them with caution and only when it is appropriate.