Search code examples
c#code-contracts

Contract doesn't work


I am stuck on a problem with System.Diagnostics.Contracts.

If I use Contract.Requires(condition), then all works as expected. But I need a custom Exception, so I tried Contract.Requires<ToShortException>(condition).

When condition was false, I expected a ToShortException but I got nothing. In the debugger I can see, that this line was ignored.

ToShortException is a public class which implements Exception and has 3 public constructors.

Has anyone an idea what I am doing wrong?

The Exception class:

public class ToShortException : Exception
{
    public ToShortException()
    {
    }

    public ToShortException(string message) : base(message)
    {
    }

    public ToShortException(string message, Exception inner) : base(message, inner)
    {

    }
}

Method of a class:

    public IDictionary<string, string> getIncident(string name)
    {
        Contract.Requires(!string.IsNullOrWhiteSpace(name)); //works fine
        Contract.Requires<ToShortException>(name.Length == 7); //got not checked

        return _original.getIncident(name);
    }

Solution

  • I found the solution. "Project Settings -> Code Contracts -> Assembly Mode" has to be "Standard Contract Requires".

    enter image description here

    The default-value was "Custom Parameter Validation".