What to do when using Contract.Assert(true) and the method must return something?
- by devoured elysium
I have a bit of code with the following logic:
//pseudo-code
foreach (element in elementList) {
if (element is whatever)
return element;
}
}
In theory, there is always one element that is whatever, so this method should pose no problems. In any case, I've put an assertion on the end of the method just to be sure:
//pseudo-code
foreach (element in elementList) {
if (element is whatever)
return element;
}
}
Contract.Assert(true, "Invalid state!");
The problem is that as this method has to return something, and the compiler doesn't understand that the assertion will break the program execution. Before using Contracts, in these kind of situations, I used to throw an Exception, which solved the problem. How would you handle this with Contract.Assert()? Returning null or default(element_type) after the Contract.Assert() call knowing it will never be called and shutting up the compiler? Or is there any other more elegant way of doing this?
Thanks