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?
The null conditional operator combines nicely with LastOrDefault()
as @Jeroen mentioned.
You can simply do:
bool ok = myObject.OtherObjects?.LastOrDefault()?.IsValid() ?? false;
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With