I have an abstract class whose constructor requires a parameter. The parameter cannot be null.
// the abstract class
[ContractClass(typeof(AbstractClassContract))]
public abstract class AbstractClass
{
// Constructor with required parameter
protected AbstractClass(SqlConnection connection)
{
Contract.Requires(connection != null);
Connection = connection;
}
protected SqlConnection Connection { get; set; }
public abstract string GetSomething();
}
The abstract class has a contract class for checking pre/post-conditions on abstract members.
// the contract class
[ContractClassFor(typeof(AbstractClass))]
public abstract class AbstractClassContract
{
public override string GetSomething()
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
The above code doesn't compile because of the error 'AbstractClass' does not contain a constructor that takes 0 arguments.
I can add a constructor, like below, and the code will compile and seems to work.
public AbstractClassContract(SqlConnection connection)
: base(connection)
{ }
But is this a valid constructor for a contract class? Will it cause a problem in some situation? My concern is that the parameter is ultimately required by the abstract class's constructor.
If it is valid, then how is .NET getting around the required parameter limitation?