Contracts for Interfaces

suggest change

Using 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…

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents