How to use a null condition statement in an empty list?

I have an object (for this simple example), for example:

public class MyObject { public ICollection<OtherObject> OtherObjects { get; set; } } public class OtherObject { public bool IsValid() { return true; } } 

Currently in my code, I:

 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 be possible to do this in one line of code like:

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

However, in this situation, an operator with a null condition will not work, since the above returns an exception

The sequence contains no elements.

So, in such situations, do I still need to use the old method of checking zeros instead of the new method using the operator with the null condition?

Or is there a better way?

+6
source share
2 answers

The null conditional statement LastOrDefault() well with LastOrDefault() , as @Jeroen mentioned.

You can simply do:

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

There are no elements in the list, but it is not null , otherwise you will get a NullReferenceException . What you can do is change it to something like this:

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

All Articles