csharp-metodos-estaticos

Static Methods and Fields in C#

  • 2 min

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

If you want to learn more, check out the Object-Oriented Programming Course

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

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;
    }
}
Copied!

In the example above, Add is a static method. To call it, we don’t need to instantiate the Utilities class:

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

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++;
    }
}
Copied!

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

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

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;
    }
}
Copied!

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.

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}");
Copied!