-2

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?

Nishant Kumar
  • 463
  • 2
  • 9
  • 18
  • 3
    What exactly _is_ your question? `sealed` classes cannot be inherited, that's the whole reason for the `sealed` keyword to exist. – René Vogt Sep 12 '16 at 12:38
  • A `sealed` class is, by definition a class from which you cannot inherit. What exactly is your question? – npinti Sep 12 '16 at 12:38
  • "The sealed modifier prevents other classes from inheriting from it" https://msdn.microsoft.com/en-gb/library/88c54tsw.aspx Whereas an "abstract class must be inherited by a class that provides an implementation of the abstract methods or properties". – Paul Zahra Sep 12 '16 at 12:38
  • i think i have clarified the question, in place of static i typed sealed – Nishant Kumar Sep 12 '16 at 13:00

2 Answers2

5

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.)

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

The abstract keyword enables to create classes and class members that are incomplete and must be implemented in a derived class whereas The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.

I think its complete for Above

durg
  • 40
  • 5
Bman
  • 1
  • 3