Static in C#

1 – What is a static class in C#

A static class (static class) in general terms is similar to a regular class, but it has a crucial difference. It cannot be instantiated. This means that you access the members of a static class directly by using the name of the static class.

We define a static class by indicating the static keyword, and when we do, all its members must also be static.

public static class Calculadora
{
    public static int Suma(int x, int y)
    {
        return x + y;
    }
}

And when we want to reference it, we do so by directly calling the class and the method, which is also static.

int resultadoSuma = Calculadora.Suma(1, 2);

 

 

2 – Static methods in C#

When you create a method, it is included inside a class, and you can use it when you instantiate that class. As explained in the example above, if a method is static, you do not need to instantiate the class, since the method does not belong to the instance. To do this, you must mark the member as static.

This functionality applies regardless of whether the class itself is static or not. For instance, in the following code:

public class Calculadora
{
    public static int Suma(int x, int y)
    {
        return x + y;
    }

    public double Media(List<int> valores)
    {
        return valores.Average();
    }
}

We access the Suma method without instantiating the class, while to use the Media method we must instantiate the class first.

int resultadoSuma = Calculadora.Suma(1, 2);
Calculadora calc = new Calculadora();
double media = calc.Media(new List<int>());

 

 

3 – When to use static

To decide whether we should create a class or a method as static, we should ask ourselves if it makes sense to call the method or the class independently of an object.

  • In the next post, we will look at "extension methods", which are static.

A very common example, especially when we first start programming, is to have a class named "Util" where we put things we need but are not sure exactly where they belong, so we put them in "Util". Typically, the methods here handle tasks like sending messages, logging, or performing parsing. These are very specific methods that do a concrete action regardless of context.

A utility class often looks like this:

public class Util
{
    public static void LogError(string mensaje)
    {
        //codigo
    }
    public static bool ComprobarCaracteresEspeciales(string frase)
    {
        //Codigo
    }
}

Since it is a static method, we can access the method directly instead of instantiating the class, i.e.: Util.LogError(). However, if the methods were not static, we would have to instantiate the class, and to access it, we would do it this way: new Util().LogError().

GitHub Link

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café