I have some code with the following logic:
foreach (element in elementList) {
if (element is whatever)
return element;
}
}
In theory, there is always one element, whatever it may be, so this method should not create problems. In any case, I put a statement at the end of the method to be sure:
foreach (element in elementList) {
if (element is whatever)
return element;
}
}
Contract.Assert(false, "Invalid state!");
The problem is that since this method must return something, and the compiler does not understand that this statement will disrupt the execution of the program. Before using Contracts, in such situations I used to throw an exception that solved the problem. How would you deal with this with Contract.Assert ()? Return null or default (element_type) after calling Contract.Assert (), knowing that it will never be called or closed by the compiler? Or is there another more elegant way to do this?