Nishant Kumar Nishant Kumar - 1 year ago 116
C# Question

Inheritance with static classes

I don't know whether this question will make sense or if it's a naive question, but I haven't been able to find a satisfactory answer.

I would like to be able to share code across multiple static classes. Is there an "equivalent" of an abstract base class for static classes (i.e. can I have one static class inherit from another one)? If not, why not? Is there another way of sharing code across multiple static classes in a manner analogous to what you do with an abstract base class?

Also, how does a static class compare to a "sealed" class?

Answer Source

You're quite right. Reflection will show that a static class is both abstract and sealed:

  public static class MyStaticTest {


  // I'm abstract
  Console.WriteLine(typeof(MyStaticTest).IsAbstract ? "I'm abstract" : "");

and that's why you can't create an instance (compile time error): new MyStaticTest();. However, reflection will show that any static class is sealed as well:

 // I'm sealed 
 Console.WriteLine(typeof(MyStaticTest).IsSealed ? "I'm sealed" : "");

and so you can't inherit from it (compile time error): public class MyClass: MyStaticTest {..}. Thus, all you can do with static class is to declare static members (static fields, properties, methods etc.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download