12 Feb 2024




Beginner
  • Static Methods Inside a Static Class: The entire class must be static, and all members of the class must be static as well. These methods are often used for utility functions that don't require any state.

  • Static Methods Inside a Non-Static Class: The class can be static or non-static. However, static methods can be called directly using the class name without needing an instance of the class. These methods can be used for common functionalities within the context of the class.

In both cases, static methods are invoked using the class name directly, making them accessible without an instance of the class.

In C#, you can have static methods inside both static classes and non-static classes. Let's illustrate the difference with an example:

Static Methods Inside a Static Class:

using System;

public static class MathUtils
{
    // Static method to calculate the factorial of a number
    public static int Factorial(int n)
    {
        if (n == 0)
            return 1;
        else
            return n * Factorial(n - 1);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Calling static method directly from the static class
        int fact = MathUtils.Factorial(5);
        Console.WriteLine("Factorial of 5: " + fact);
    }
}

In this example, MathUtils is a static class containing a static method Factorial(). Since the class is static, all its members must be static as well. We call the Factorial() method directly using the class name MathUtils.

Static Methods Inside a Non-Static Class:

using System;

public class MathOperations
{
    // Static method to calculate the power of a number
    public static double Power(double x, double y)
    {
        return Math.Pow(x, y);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Calling static method from a non-static class
        double result = MathOperations.Power(2, 3);
        Console.WriteLine("2 to the power of 3: " + result);
    }
}

In this example, MathOperations is a non-static class containing a static method Power(). This is perfectly legal in C#. We can call the static method Power() directly using the class name MathOperations.

c-sharp
static-methods
static-class