Language: EN

csharp-metodos-estaticos

Static Methods and Fields in C#

Static methods and fields are those that do not belong to a particular instance, but belong directly to the class itself. This means that we can call them directly from the class, without needing to create an instance of it.

Static methods and fields have their advantages, but also their drawbacks. If you want to learn more about them, and when to use them and when not to, read the article I have provided.

Static Methods

To create a static method, we add the static keyword before the return type.

public class Utilities
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

In the previous example, Add is a static method. To call it, we do not need to instantiate the Utilities class:

int result = Utilities.Add(5, 3);

Static Fields

A static field, similarly, is a variable that belongs to the class itself and not to specific instances of the class. All objects of the class share the same static field.

public class Counter
{
    public static int Count;

    public Counter()
    {
        Count++;
    }
}

In this example, Count is a static field that is incremented each time a new instance of Counter is created.

Counter c1 = new Counter();
Counter c2 = new Counter();
Console.WriteLine(Counter.Count); // Output: 2

Practical Example

Let’s create a class that combines static fields and methods to illustrate how they can be used together.

public class Calculator
{
    // Static field
    public static int TotalOperations = 0;

    // Static method
    public static int Add(int a, int b)
    {
        TotalOperations++;
        return a + b;
    }

    public static int Subtract(int a, int b)
    {
        TotalOperations++;
        return a - b;
    }

    public static int Multiply(int a, int b)
    {
        TotalOperations++;
        return a * b;
    }

    public static int Divide(int a, int b)
    {
        TotalOperations++;
        return a / b;
    }
}

In this example:

  • TotalOperations is a static field that counts the total number of operations performed.
  • Add, Subtract, Multiply, and Divide are static methods that perform arithmetic operations and update the static field TotalOperations.

Using the Calculator Class

Now we can use the static fields of the Calculator class without creating an instance of the class.

int sum = Calculator.Add(10, 5);
int subtraction = Calculator.Subtract(10, 5);
int multiplication = Calculator.Multiply(10, 5);
int division = Calculator.Divide(10, 5);

Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Subtraction: {subtraction}");
Console.WriteLine($"Multiplication: {multiplication}");
Console.WriteLine($"Division: {division}");
Console.WriteLine($"Total operations: {Calculator.TotalOperations}");