-5

Consider these statements in C#:

foreach (var sample in channel.Data)                                                                                                                
{                                                                                                                                                   
    if (sample.TimeStamp < placeholderMinLimit) continue;
}

This code returned on execution a NullReferenceException and review within the VS2019 IDE shows that the variable "sample" has value null. Meanwhile, "channel.Data" is not null, and has many thousand data points.

So, the question is, how is it possible for "sample" to be set to a value of null?

wrb
  • 9
  • 2
  • 4
    `yield null` works from within the iterator. Enumerables don't have to return only non-null items. –  Mar 09 '21 at 18:27
  • 7
    `channel.Data` is a collection of some sort evidentially, but that doesn't mean the objects contained in that collection are not null. – Trevor Mar 09 '21 at 18:27
  • 1
    Can any sample instance be `null` itself? (not the array, but an entry in the array) – Can Poyrazoğlu Mar 09 '21 at 18:27

1 Answers1

1

How may a C# foreach interator yield a null reference

Easy

channel.Data = new Sample[] { null, null, null };
foreach (var sample in channel.Data) {                                  
    if (sample.TimeStamp < placeholderMinLimit) 
        continue;
}

If you want to avoid this, just filter it

foreach ( var sample in channel.Data.Where( x => x != null) )
{   
    if (sample.TimeStamp < placeholderMinLimit) 
        continue;
}
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • 1
    Side note (pure academical): `x => x is object` or `x => x is not null` is a tiny bit better then `x != null`. Technically, it may occure that `!=` operator is *overloaded* and returns `true` when `x` is `null`. Another (wordy) option is `!ReferenceEquals(null, x)` – Dmitry Bychenko Mar 09 '21 at 18:37