Skip to Content
All posts

Static vs instance methods In C#

2 min read ·  — #csharp-interview#junior#oop

Static vs instance methods In C#

Instance Methods

Instance methods in C# belong to an instance of a class. This means you have to create an object from a class to use these methods. They operate on the state of the object, meaning they can access and modify instance variables.

Here's a simple example:


public class Dog
{
    private string name;

    public Dog(string name)
    {
        this.name = name;
    }

    public void Bark()
    {
        Console.WriteLine("{0} says: Woof!", name);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog("Spot");
        myDog.Bark(); // Spot says: Woof!
    }
}

In this example, Bark() is an instance method. We create a Dog object named myDog, and then we can call the Bark() method on this object.

Static Methods

On the other hand, static methods belong to the class itself and not to any specific object. They can't directly access instance variables or methods in the class. They're often used for utility methods which don't depend on the state of an object.

Here's a simple example:


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

class Program
{
    static void Main(string[] args)
    {
        int result = MathHelper.Add(5, 7); // No need to create an instance
        Console.WriteLine(result); // 12
    }
}

In this example, Add() is a static method. We don't have to create a MathHelper object to use this method; instead, we can call it directly on the class.

Key Differences

Here are the key differences between instance and static methods:

Statefulness: Instance methods are stateful. They belong to an object and can operate on the state of the object. In contrast, static methods are stateless. They don't belong to a specific object and can't directly operate on an object's state.

Access: You can call an instance method on an object. You have to instantiate an object from the class before you can use the method. You can call a static method on the class itself, without creating an object.

Variables: Instance methods can access instance variables and other instance methods directly. Static methods can't access instance variables or methods directly because they don't belong to an instance of the class. However, they can access static variables and other static methods.

Remember these points, and you'll be well-prepared for questions on static and instance methods in your technical interview.