C# code: Resharper suggests changing the accessibility of a public
constructor in an abstract
class to protected
, but it does not state the rationale behind this.
Can you shed some light?
views:
418answers:
3
+16
A:
Simply because being public makes no sense on an abstract class. An abstract class by definition cannot be created directly. It can only be created by creating an instance of a derived type. Therefore the only types that should have access to a constructor are derived types and hence protected makes much more sense that public. It more accurately describes the accessibility.
JaredPar
2009-04-17 19:33:30
In other words: why would you want to pollute other people's IntelliSense with useless garbage?
André Neves
2009-04-17 19:34:21
@Andre constructors only show in intellisense for new and base calls. Typically abstract classes are filtered out of new before accessibility is considered because checking for abstract is very easy and cheap.
JaredPar
2009-04-17 19:38:26
Really -1'd for this answer? At least give a reason
JaredPar
2009-04-17 19:52:07
A:
It is a good OO practice to do do that:
public abstract class ExampleAbstractClass
{
protected ExampleAbstractClass()
{
}
}
You want only the inheritor classes to have access to the constructor, and the only way to do that is making the constructor protected. Keep in mind, when you add parameters to these constructors, it is a whole another discussion.
CodeToGlory
2009-04-17 19:39:38
What makes it different when you add parameters? The constructor will still only be called by derived classes.
Dusty Campbell
2009-04-17 19:42:28
It will force all the inheritor constructors to have the parameter in their signature, whether needed or not.
CodeToGlory
2009-04-17 19:54:34
A:
Similarly, static classes don't even get a default parameterless contructor...
Charles Bretana
2009-04-17 19:42:39
How is this similar? Static classes don't get a default constructor because they have no need for them.
Samuel
2009-04-17 19:44:40
Constructors for abstract classes cannot be public or internal for the same reason... (It represents an illegal action - one that is not consistent with the types' definition)
Charles Bretana
2009-04-18 01:54:30