37

This question is out of curiosity. Is there a difference between:

public abstract class MyClass
{
    public MyClass()
    {
    }
}

and

public abstract class MyClass
{
    protected MyClass()
    {
    }
}

Thanks.

3 Answers 3

32

They are the same for all practical purposes.

But since you asked for differences, one difference I can think of is if you are searching for the class's constructor using reflection, then the BindingFlags that match will be different.

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var constructor = typeof(MyClass).GetConstructor(flags, null, new Type[0], null);

This will find the constructor in one case, but not the other.

16

You shouldn't have a public constructor in an Abstract class Constructors on abstract types can only be called by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type with a public constructor is incorrectly designed.

have a look here for details http://msdn.microsoft.com/en-us/library/ms182126.aspx

9
  • 1
    @Shekhar: please don't post MSDN links to old versions. Readers clicking links within that document will be led to more old versions. Dec 26, 2010 at 0:08
  • @John oh thanx for editing my post. I forgot to look for the version on the page.... :P Dec 26, 2010 at 0:15
  • 5
    "is incorrectly designed" is quite different from "can't have".
    – Ben Voigt
    Dec 26, 2010 at 1:07
  • 1
    This is a very late post, but if you use any IOC or DI style approaches, having a public constructor in the abstract class does make sense in certain cases, where you want to minimize code duplication.
    – code4life
    Apr 4, 2013 at 20:57
  • 2
    @code4life - It would be awesome if you could give an example or post a link to an example. Not ripping on your comment by any means but I am interested by what you mean. Sep 4, 2013 at 2:33
2

In terms of future use of this code, there is no difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.