Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-6.0

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?

like image 342
Ivan-Mark Debono Avatar asked Jun 07 '16 10:06

Ivan-Mark Debono


2 Answers

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

You can simply do:

bool ok = myObject.OtherObjects?.LastOrDefault()?.IsValid() ?? false;
like image 121
Toxantron Avatar answered Oct 01 '22 20:10

Toxantron


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();              
like image 43
Fabjan Avatar answered Oct 01 '22 20:10

Fabjan