Sealed vs. Static Classes in C#: Understanding Class Restrictions
Explore the differences between sealed and static classes in C#. This tutorial clarifies when to use each type of class, explaining how `sealed` prevents inheritance and how `static` prevents instantiation, improving your understanding of class design and code optimization.
Sealed vs. Static Classes in C#
Both sealed and static classes in C# impose restrictions, but in different ways. Understanding their differences is crucial for writing efficient and well-structured code.
Sealed Classes
A sealed class in C# prevents inheritance. This means you cannot create a derived class (a subclass) from a sealed class. It's useful when you want to prevent a class from being extended or modified in the future. Sealed classes can improve performance by avoiding runtime checks for inheritance.
Syntax
sealed class MyClass {
// ... class members ...
}
Example
sealed class Vehicle {
public void Drive() { Console.WriteLine("Driving..."); }
}
// class Car : Vehicle {} // This would cause a compiler error
Static Classes
A static class in C# cannot be instantiated (you can't create objects of it). All members of a static class must also be static. Static classes are commonly used for utility functions or helper methods that don't require an instance to operate. They can improve runtime performance and reduce memory usage because no objects are created.
Syntax
static class MathHelpers {
public static int Add(int a, int b) { return a + b; }
}
Example
static class MathHelpers {
public static int Add(int a, int b) { return a + b; }
}
class Program {
static void Main(string[] args) {
int result = MathHelpers.Add(5, 3); // Accessing directly without creating an instance
Console.WriteLine(result); // Output: 8
}
}
Key Differences: Sealed vs. Static
Feature | Sealed Class | Static Class |
---|---|---|
Inheritance | Cannot be inherited | Cannot be inherited |
Instantiation | Can be instantiated | Cannot be instantiated |
Members | Can have static and instance members | Must have only static members |
Constructor | Has a constructor | Does not have a constructor |
Polymorphism | Supports polymorphism | Does not support polymorphism |