Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't this contract assertion be proven?

I have a class that looks something like this:

class Foo
{
    private IEnumerable<Bar> bars;

    ...

    private void DoSomething()
    {
        Contract.Requires(bars != null);
        Contract.Requires(bars.Any());

        Bar result = bars.FirstOrDefault(b => SomePredicate) ?? bars.First();
        Contract.Assert(result != null); // This asserts fails the static checker as "cannot be proven"
    }
}

As far as I can tell, Contracts has all the information it needs to know that result will not be null. bars has at least one element in it. If one of those elements matches SomePredicate, result will be the first such element. If not, result will be the first element in bars.

Why does the assertion fail?

like image 303
Matthew Avatar asked Nov 24 '25 23:11

Matthew


1 Answers

The colection bars could still contain an item that is null. If that item is the first item then result can still be null.

like image 154
Sven Avatar answered Nov 27 '25 14:11

Sven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!