What to do when using Contract.Assert(true) and the method must return something?
Posted
by devoured elysium
on Stack Overflow
See other posts from Stack Overflow
or by devoured elysium
Published on 2010-05-06T06:58:10Z
Indexed on
2010/05/06
7:08 UTC
Read the original article
Hit count: 177
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
© Stack Overflow or respective owner