Protected Constructors For Abstract Classes

One code modification Resharper 4.0 will suggest is that if a public constructor is located in an abstract class, it should be adjusted to use the protected access modifier if currently public:

Resharper Constructor Protected Constructors For Abstract Classes

So, from this:

C#:
  1. public abstract class AbstractClass
  2. {
  3. public AbstractClass()
  4. {
  5. }
  6. }

To this:

C#:
  1. public abstract class AbstractClass
  2. {
  3. protected AbstractClass()
  4. {
  5. }
  6. }

So, why is this a good code edit?

Well, having a public constructor on an abstract class in the terms of code architecture is irrational since the abstract class can’t be instantiated directly; it is instead created by instantiating the deriving type. Thus only derived types have access to the abstract class constructor. Protected more adequately describes a germane access modifier for the constructor as well as ensuring requisite inheritor types have constructor access.

More noticeably, appropriate access modifier decoration will in turn not populate Intellisence with a bunch of useless crap :)

  • Share/Bookmark

4 Comments »

  1. Did not know about this, great tip
    (even though it’s categorized under SharePoint Development. You need a C# category or something :) )!

    Comment by James Fortner — May 12, 2009 @ 8:07 am

  2. Indeed, I did have some abstract classes that were doing this. Fixing em up right now!

    Comment by Kirk Kerr — May 12, 2009 @ 8:08 am

  3. I just don’t see why this is important. What are the relevant arguments for an implementation across a whole product for this…improvement.

    Comment by James Tyson — May 12, 2009 @ 8:26 am

  4. @James:

    What? The justifications you are asking about are located in the article.

    Comment by Adam Buenz — May 12, 2009 @ 8:30 am

RSS feed for comments on this post. TrackBack URL

Leave a comment