Martin Mazza Dawson Martin Mazza Dawson - 2 months ago 19
C# Question

Using Null coalescing operator in foreach with select expression

foreach (var item in Model.PublishedSong.RelatedSongs.Select((value, i) => new { value, i }) ?? Enumerable.Empty <dynamic>())
{

}


Related Songs may or may not be null, is there any way to use null coalescing operator here? I still get the error message:


value cannot be null

Answer

If RelatedSongs is null, calling Select on it will throw a NullReferenceException, because the null coalescing operator is evaluated only after the left-hand side is resolved. And since resolving the left hand side results in an exception, it won't do you any good.

If you're using C# 6.0, you can use the Null Propagation operator - ?. - to call Select only if RelatedSongs isn't null, and use the Null Coalescing operator otherwise:

// This will return null if Relatedsongs is null, or call Select otherwise.
foreach (var item in Model.PublishedSong.RelatedSongs?.Select((value, i) => new { value, i })  
                             ?? Enumerable.Empty <dynamic>())
{
}

If you're using C# 5 or earlier, you'll have to check for null manually:

foreach (var item in Model.PublishedSong.RelatedSongs != null 
                             ? Model.PublishedSong.RelatedSongs.Select((value, i) => new { value, i }) 
                             : Enumerable.Empty <dynamic>())
{
}
Comments