Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16340

How to use the null-conditional operator on an empty list?

I have an object (keeping it simple for this example), such as:

public class MyObject
{
    public ICollection<OtherObject> OtherObjects { get; set; }
}

public class OtherObject
{
    public bool IsValid() { return true; }
}

Currently in my code I do:

bool ok = false;
if (myObject.OtherObjects != null && myObject.OtherObjects.Count > 0)
{
    var last = myObject.OtherObjects.Last();
    ok = last.IsValid();
}

Now, with C#6.0, it would have been possible to do this in one line of code as:

bool? ok = myObject.OtherObjects?.Last()?.IsValid();

However, in this situation, the null-conditional operator won't work because the above returns an exception

The sequence contains no elements.

So in these kinds of situations, do I still need to use the old method of checking for nulls instead of the new method using the null-conditional operator?

Or is there a better way?

Upvotes: 9

Views: 3889

Answers (2)

Toxantron
Toxantron

Reputation: 2398

The null conditional operator combines nicely with LastOrDefault() as @Jeroen mentioned.

You can simply do:

bool ok = myObject.OtherObjects?.LastOrDefault()?.IsValid() ?? false;

Upvotes: 6

Fabjan
Fabjan

Reputation: 13676

The list contains no elements, but it is not null otherwise you'd get a NullReferenceException. What you can do is change it to something like that :

bool? ok = myObject.OtherObjects?.Any() ?? false && myObject.OtherObjects.Last().IsValid();              

Upvotes: 1

Related Questions