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 derived class and sealed means class can not be derived. Conflicting statements!!?
Well actually the catch is in the meaning of abstract class. Creating abstract class means that instance of a class can not be created. That is why you can have following class in c#:
 public abstract class MyFundooClass  
   {  
     //abstract class without any abstract members.      
   }  
So now you are clear that abstract means class can not be instantiated. But what if someone decided to derive your class and create an instance of it?
For ex:
 public class MyFundooClassImpl : MyFundooClass  
   {  
   }  
....
 void SomeFunc()  
 {  
   MyFundooClass obj= new MyFundooClassImpl(); //Ohh some has an instance of MyFundooClass !!??  
 }  
Here the sealed keyword comes to rescue. Sealed means class can not 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 question is why would any one 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 in to a abstract sealed class!. And just because you can not create any instance of such class compiler won't let to define any instance member, so you must have only static members in such class.

Happy coding!!

Comments

Post a Comment

Popular posts from this blog

Data Binding in .net

काहे की दोस्ती

C# Polymorphic types conversion with Generics