Sunday, February 10, 2013

How do you prevent a class from being inherited? Are there any such classes in the .NET framework? (C#)

In order to prevent a class in C# from being inherited, the keyword sealed is used. Thus a sealed class may not serve as a base class of any other class. It is also obvious that a sealed class cannot be an abstract class. Code below...
//C# Example
sealed class ClassA
{
public int x;
public int y;
}
No class can inherit from ClassA defined above. Instances of ClassA may be created and its members may then be accessed, but nothing like the code below is possible...
class DerivedClass : ClassA { } // Error

Sealed classed in .Net framework are : System.Drawing, System.Collections etc.

No comments: