In C#, methods can be static or instance. Knowing the difference helps you organize your code.
🏛️ Static Methods
- Belong to the class itself, not to any object.
- Call them using the class name.
1
2
3
4
5
6
7
8
9
10
class MathTools
{
public static int Double(int n)
{
return n * 2;
}
}
// Usage:
int result = MathTools.Double(5); // 10
👤 Instance Methods
- Belong to an object (an instance of a class).
- Call them on specific objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Person
{
public string Name;
public void SayHello()
{
Console.WriteLine($"Hello, I am {Name}!");
}
}
// Usage:
Person p = new Person();
p.Name = "Sam";
p.SayHello(); // Hello, I am Sam!
💡 When to Use Each?
- Use static when the method doesn’t use any object data.
- Use instance when the method works with specific object data.
Try It!
Write a class Dog
with an instance method Bark()
that prints “Woof!”.
1
2
3
4
5
6
7
class Dog
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}
Next: Object-oriented programming in C#!