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 the need to create an instance of it.
If you want to learn more about Static Methods and Variables
check out the Object-Oriented Programming Course read more
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 provided.
Static Methods
To create a static method, we add the keyword static
before the return type.
public class Utilities
{
public static int Add(int a, int b)
{
return a + b;
}
}
In the example above, Sumar
is a static method. To call it, we do not need to instantiate the Utilidades
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, Cuenta
is a static field that increments every time a new instance of Contador
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:
- **TotalOperaciones** is a static field that counts the total number of operations performed.
- **Sumar**, **Restar**, **Multiplicar**, and **Dividir** are static methods that perform arithmetic operations and update the static field `TotalOperaciones`.
### Using the Calculator Class
Now we can use the static fields of the `Calculadora` class without creating an instance of the class.
```csharp
int sum = Calculator.Add(10, 5);
int subtract = Calculator.Subtract(10, 5);
int multiplication = Calculator.Multiply(10, 5);
int division = Calculator.Divide(10, 5);
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Subtraction: {subtract}");
Console.WriteLine($"Multiplication: {multiplication}");
Console.WriteLine($"Division: {division}");
Console.WriteLine($"Total operations: {Calculator.TotalOperations}");