0

http://msdn.microsoft.com/en-us/library/ms182126.aspx

Microsoft Design Guidelines say that Abstract Types should not have a Constructor.

To me, it seems very plausible that most classes that derive from an abstract class will have a constructor very similar to, if not identical to, its base.

If for no other reason but to follow DRY, is it really terrible to have abstract classes with Constructors if it means that all your derived classes now only need to put

    public DerivedClass()
        : base()
    {

    }

Or is there something that I am missing?

JHixson
  • 1,512
  • 2
  • 14
  • 29
  • 3
    This question has been asked a few times before. This answers it pretty well: http://stackoverflow.com/questions/2299037/abstract-constructor-in-c-sharp – foolmoron Oct 11 '13 at 20:22
  • Right, specifically the answer says "It is perfectly reasonable to have a constructor defined, typically as protected, in order to define some common set up code for all derived classes." I suppose that my Questions is: If that is the case, why the guideline against it? – JHixson Oct 11 '13 at 20:28
  • 1
    The text on MSDN is geared toward `public` constructors which are indeed nonsense. Is the warning given for a `protected` constructor as well? That would surprise me. – H H Oct 11 '13 at 20:30
  • The guideline specifically calls out changing public constructors on abstract classes to protected as a correction. – Preston Guillot Oct 11 '13 at 20:34

1 Answers1

1

There's nothing to prevent you from doing that but by definition abstract classes are those that cannot be instantiated. So if you create a constructor, make it protected, not public otherwise your class won't meet the definition of abstract.

The guideline you mentioned further explains:

Cause: A public type is abstract and has a public constructor.

and

Rule description: Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.

How to Fix Violations: To fix a violation of this rule, either make the constructor protected or do not declare the type as abstract.

Community
  • 1
  • 1
Szymon
  • 42,577
  • 16
  • 96
  • 114