What to do when using Contract.Assert (true) and the method should return something?

I have some code with the following logic:

//pseudo-code
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:

//pseudo-code
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?

+5
2

var result = null;
foreach (element in elementList) {
    if (element is whatever)
        result = element;
        break;
    }
}

Contract.Assert(result != null, "Invalid state!");
return result;

, .

return elementList.Where( e => e is whatever).First();

, @devoured ,

,

return elementList.First( e => e is whatever);

end edit

, .

,

var results = elementList.Where( e => e is whatever);
Contract.Assert(results.Count() == 1, "Boo");
return results.First();

.

+2

, Contract.Requires (.. ), Contract.Assert . , elementList , .

, Assert(false), , , Assert(false).

, :

//precondition (checked only in debug builds)
Contract.Require(elementList.Where(e => e is whatever).Count > 0,"elementList requires at least one element meeting condition whatever");
//do work (throws in release builds, never reached in debug ones)
return elementList.First( e => e is whatever);
+1

All Articles