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(false, "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
You could go with
It introduces a break, but it does look cleaner around the return.
Even cleaner would be
Edit as @devoured pointed out the above would hit the whole list
cleaner without the where
end edit
That just blows up if there is nothing found.
But if you really want the assert it could be
but that will iterate the whole list too.