Search code examples
c#code-contracts

combine contracts precondition to return error once?


HI there

I was wondering if there is anyway to combine all Contract.Requiere in a method, so say something like this happens

public void MyMehod(Order var1, Cust var2)
{
   Contract.Requires<ArgumentException>(var1 != null);
   Contract.Requires<ArgumentException>(var2 != null);  
   //...
}

And that if I call MyMehtod and both var1 and var2 are null I get both error messages?

(maybe the example is not great) but the idea is that if call the method, I want to know everything that's wrong with it So, does anyone know if its possible to combine the Contracts so that I get one error message back?


Solution

  • One really crufty way - which doesn't scale to lots of arguments - is to first have a contract which will fail if both are null:

    Contract.Requires<ArgumentException>(var1 != null || var2 != null);
    

    or

    Contract.Requires<ArgumentException>(!(var1 == null && var2 == null));
    

    ... but then you'd still need the two individual ones. I don't think I'd recommend actually doing this, but it's the only thing I can think of offhand.