is nullcheck with keyword "is" safe?

136 views Asked by At

I, in a hurry, typed the following code:

List<Foo> myList = feedMyList();
var bar = myList.FirstOrDefault(x => something);

if (bar is null)
{
    // something
}

My first thought was that I was writing something wrong, so I experienced a bit with C# interactive:

> var list = new List<string>();
> list.FirstOrDefault()
null
> list.FirstOrDefault() is null
true // As expected
> list.Add("abcdef");
> list.FirstOrDefault() is null
false // As expected
> list.FirstOrDefault(x => x.Length > 120) is null
true // As expected

and everything was correct. Is it safe to write (and use) if (bar is null) or am I missing potential issues?

0

There are 0 answers