public abstract sealed class MyFundooClass {}





5.00/5 (2 votes)
public abstract sealed class MyFundooClass {}
Ever heard of a class that is abstract
as well as sealed
? Sounds impossible, right? abstract
means some functions must be defined in the derived class and sealed
means class cannot be derived. Conflicting statements!!? Well, actually the catch is in the meaning of abstract
class. Creating abstract
class means that instance of a class cannot be created. That is why you can have the following class in C#:
public abstract class MyFundooClass
{
//abstract class without any abstract members.
}
So now, you are clear that abstract
means class cannot be instantiated. But what if someone decided to derive your class and create an instance of it? For example:
public class MyFundooClassImpl : MyFundooClass
{
}
void SomeFunc()
{
MyFundooClass obj= new MyFundooClassImpl(); //Ohh some has an instance of MyFundooClass !!??
}
Here, the sealed
keyword comes to the rescue. Sealed
means class cannot be derived. So now, you can write your class as:
public abstract sealed class MyAbstractClass
{
}
Now, no one can derive your class, and no one can create any instance of it. Happy!! But, the question is why would anyone want to create a class that is abstract sealed
? And the answer is, ever heard of static
class?
public static class MyFundooClass
{
}
The static
class in C# are equivalent to abstract sealed
class. In fact, C# compiler won't let you write:
public abstract sealed class MyAbstractClass //Error!!!
{
}
But if you compile a static
class, and investigate the IL, you would be surprised to see that IL is:
.class public abstract auto ansi sealed beforefieldinit C_Sharp_ConsoleApp.MyFundooClass
extends [mscorlib]System.Object
{
}
So, a static
class in C# actually gets compiled into an abstract sealed
class!. And just because you cannot create any instance of such class, the compiler won't let you define any instance member, so you must have only static
members in such class.
Happy coding!!