C# Sealed Class
In C#, a class can be marked as sealed to prevent it from being inherited by other classes. When a class is marked as sealed, it cannot be used as a base class for other classes. In this tutorial, we'll discuss how to use sealed classes in C#.
Syntax
The syntax for defining a sealed class in C# is as follows:
sealed class MyClass {
// class members
}
The sealed keyword is used before the class keyword to indicate that the class cannot be inherited.
Example
Let's say we want to define a class that represents a single point in two-dimensional space. We don't want any other class to inherit from this class, so we'll mark it as sealed:
sealed class Point2D {
public int X { get; set; }
public int Y { get; set; }
public Point2D(int x, int y) {
X = x;
Y = y;
}
}
Now, we can use the Point2D class in our code, but we cannot create a subclass of it:
Point2D p = new Point2D(10, 20);
Console.WriteLine(p.X); // Output: 10
Output
When we run the example code above, the output will be:
10
This is because we created an instance of the Point2D class, set its X and Y properties, and printed the value of its X property to the console.
Explanation
In the example above, we defined a class called Point2D that represents a single point in two-dimensional space. We marked the class as sealed to prevent it from being inherited by other classes. We then created an instance of the Point2D class and set its X and Y properties. Finally, we printed the value of its X property to the console.
Use
Sealed classes are useful when you want to prevent other classes from inheriting from them. You might want to do this to protect the integrity of the class, or to ensure that it is used only in a certain way.
Important Points
- Sealed classes cannot be used as base classes for other classes.
- Sealed classes cannot be inherited by other classes, but they can still implement interfaces.
- Sealing a class can improve performance because it prevents the JIT compiler from performing virtualization optimizations.
Summary
In this tutorial, we discussed how to use sealed classes in C#. We covered the syntax, example, output, explanation, use, and important points of sealed classes in C#. With this knowledge, you can now use sealed classes in your C# code to prevent other classes from inheriting them and ensuring the integrity of the class.