Static vs Non-Static in C#: Key Differences and Usage
static members belong to the class itself and are shared across all instances, while non-static members belong to individual objects and require an instance to be accessed. Static members can be accessed without creating an object, but non-static members need an instance of the class.Quick Comparison
Here is a quick side-by-side comparison of static and non-static members in C#.
| Factor | Static | Non-Static |
|---|---|---|
| Belongs to | Class itself | Instance (object) |
| Access | Without creating object | Requires object instance |
| Memory | Single copy shared | Separate copy per instance |
| Use case | Utility methods, constants | Instance-specific data and behavior |
| Can access | Only static members | Both static and non-static members |
| Inheritance | Can be inherited but not overridden | Can be overridden in derived classes |
Key Differences
Static members belong to the class itself, so they are shared by all instances. You can call a static method or access a static variable without creating an object of the class. This is useful for utility functions or data that should be common to all objects.
Non-static members belong to individual objects. Each object has its own copy of non-static fields and can call non-static methods that operate on that object's data. You must create an instance of the class to use these members.
Also, static methods cannot access non-static members directly because they do not belong to any instance. Non-static methods can access both static and non-static members. This distinction helps organize code and memory usage efficiently.
Code Comparison
This example shows a static method calculating the square of a number without needing an object.
using System; public class Calculator { public static int Square(int number) { return number * number; } } class Program { static void Main() { int result = Calculator.Square(5); Console.WriteLine($"Square of 5 is {result}"); } }
Non-Static Equivalent
This example shows a non-static method that requires creating an object to calculate the square.
using System; public class Calculator { public int Square(int number) { return number * number; } } class Program { static void Main() { Calculator calc = new Calculator(); int result = calc.Square(5); Console.WriteLine($"Square of 5 is {result}"); } }
When to Use Which
Choose static when you need a method or data that is common to all instances, like utility functions or constants, and you want to avoid creating unnecessary objects. Use non-static when the behavior or data depends on individual object state and you need separate copies for each instance. Static is great for shared resources, while non-static fits object-specific logic.