Contracts for Interfaces
suggest changeUsing Code Contracts it is possible to apply a contract to an interface. Declare an abstract class that implements the interface. Tag the interface with ContractClassAttribute and the contract class with ContractClassForAttribute.
C# Example…
[ContractClass(typeof(MyInterfaceContract))]
public interface IMyInterface
{
string DoWork(string input);
}
// Never inherit from this contract definition class.
[ContractClassFor(typeof(IMyInterface))]
internal abstract class MyInterfaceContract : IMyInterface
{
private MyInterfaceContract() { }
public string DoWork(string input)
{
Contract.Requires(!string.IsNullOrEmpty(input));
Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
throw new NotSupportedException();
}
}
public class MyInterfaceImplementation : IMyInterface
{
public string DoWork(string input)
{
return input;
}
}
Static Analysis Result…
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents