Search code examples
c#.netcode-contracts

Using Code Contracts to define an immutable interface?


Can I use Code Contracts to define read-only, invariant properties on an interface? I.e. properties which always yield the same value after instantiation?


Solution

  • First a note on terminology in .NET:

    • read-only: The interface you happen to have cannot be used to mutate the object or collection
    • immutable: Nothing can mutate the object or collection

    Now back to your question.

    All property getters are implicitly marked as "Pure" in .NET Code Contracts. This means that reading from the getter should never have a visible side-effect.

    In a strict sense, if you have an abstract interface with only read-only properties then the whole interface is considered to be read-only.

    However, it sounds like what you really want is a way to mark an interface as immutable and have the underlying classes inherit that status. Unfortuantely there is no way to do that, abstract interfaces can only add functionality. And the best that Code Contracts can do is ensure the functionality was added correctly.

    Summary

    No, it doesn't support that.