Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prove to CodeContracts that IEnumerable<T>.Single() never returns null?

I have the following code snippet:

    public static string returnString()
    {
        string[] stringList = { "a" };

        if (stringList.Count() != 1)
        {
            throw new Exception("Multiple values in list");
        }

        var returnValue = stringList.Single();

        Contract.Assert(returnValue != null, "returnValue is null");

        return returnValue;
    }

CodeContract says:

CodeContracts: assert unproven. Are you making some assumption on Single that the static checker is unaware of?

In my understanding, Single() never returns null - it returns either the exactly only value of the IEnumerable or it throws an exception. How can I proof this to the code analyzer?

like image 573
Rufus Buschart Avatar asked Dec 19 '22 04:12

Rufus Buschart


1 Answers

In my understanding, Single() never returns null

Not true -

string[] a = new string[] {null};

bool check = (a.Single() == null);  // true

It returns either the exactly only value of the IEnumerable or it throws an exception.

That is correct - so if the collection contains just a single null value then Single will return null.

like image 122
D Stanley Avatar answered Jan 04 '23 23:01

D Stanley