I'm reading 'C# in depth' by Jon Skeet currently and there's an example depicting Code Contracts with an abstract class implementing an interface which features as an accompanying class for the interface, in Code Contracts' terms: a 'Contract Class For' (I'm not going into details about the workings of Code Contracts here).
The interface (p. 467):
[ContractClass(typeof(ICaseConverterContracts))]
public interface ICaseConverter
{
string Convert(string text);
}
The abstract class:
[ContractClassFor(typeof(ICaseConverter))]
internal abstract class ICaseConverterContracts : ICaseConverter
{
public string Convert(string text)
{
Contract.Requires(text != null);
Contract.Ensures(Contract.Result<string>() != null);
return default(string); // returns dummy value
}
// prevents instantiation
private ICaseConverterContracts() { }
}
(I've added the comments in the code based on comments in the book)
My question:
Why is it necessary to add the private constructor to this abstract class when you can't instantiate an abstract class to begin with? What am I not getting?
While abstract
classes can't be directly instantiated, the access modifier (e.g. private
) on the constructor matters when they are inherited. By making the constructor private
instead of the default, you are making it so that no inherited class can be constructed. Since this is the only constructor, you are effectively making the class sealed
, since no inheriting class (unless it's nested in ICaseConverterContracts
) can compile (in C#, at least).
I'm guessing that the Code Contracts code instantiates the class via reflection, or some other way that bypasses the problem of the constructor being private
.