11
difference between static and sealed class
difference between static and sealed class
Both static and sealed classes restrict inheritance in C#, but they serve very different purposes.
A static class is a class that:
// Static class declaration
public static class MathHelper
{
// Static method
public static int Add(int a, int b)
{
return a + b;
}
}
// Calling static method directly using class name
int result = MathHelper.Add(5, 3);
| Feature | Static Class |
|---|---|
| Can create object? | No |
| Can inherit? | No |
| Can be inherited? | No |
| Contains instance members? | No |
| Contains static members? | Yes |
| Constructor allowed? | Only static constructor |
Use static classes when you need:
Examples:
MathConsoleFileA sealed class is a normal class that:
// Sealed class declaration
public sealed class Employee
{
// Instance property
public string Name { get; set; }
// Instance method
public void Display()
{
Console.WriteLine(Name);
}
}
// Creating object of sealed class
Employee emp = new Employee();
// Setting property value
emp.Name = "John";
// Calling method
emp.Display();
// ❌ Error: Cannot derive from sealed type
public class Manager : Employee
{
}
| Feature | Sealed Class |
|---|---|
| Can create object? | Yes |
| Can inherit from other class? | Yes |
| Can be inherited? | No |
| Contains instance members? | Yes |
| Contains static members? | Yes |
| Supports constructors? | Yes |
| Static Class | Sealed Class |
|---|---|
| Cannot be instantiated | Can be instantiated |
| Only static members allowed | Both instance & static members allowed |
| Cannot inherit or be inherited | Can inherit, but cannot be inherited |
| Used for utility/helper functionality | Used to stop further inheritance |
| Automatically sealed | Explicitly marked sealed |
Think of a toolbox:
Example:
Math.Sqrt(25);
Think of a final product:
A static class is internally treated as:
abstractsealedThis combination means:
abstract)sealed)But C# provides the static keyword for cleaner syntax and intent.
static when:sealed when: