While
yield return o
does return null here, the question is what are you doing with it afterwards? Basically, the
yield return null
is sending null back up to the
Points
call and is returned back to the level above. What you need to do in this call is wrap the
yield return o
up so that it doesn't
yield
if it gets null. Rewrite it like this:
public IEnumerable<dynamic> Points
{
get
{
foreach (var o in GetData())
{
if (o != null)
{
yield return o;
}
}
}
}
Now you can call this confidently knowing that you will get data without null values outside.
Okay, I see the issue you are getting now. The point that's causing you a problem is a misunderstanding of what
yield
actually does here. Basically, while it yields a value back to the caller, it will still continue processing inside this method. It doesn't act like a return statement, it merely yields the value back to the caller. Potentially, with a yield statement, you could have multiple values coming out of one call.
So, the fact that the next statement works on Model.Plan.Points may fail because Model.Plan or Model.Plan.Points is null. You could work around this by putting that part in an else clause.
[Edit]Here's a way to really blow your mind with a yield - assume that the model is fully populated :
private IEnumerable<dynamic> GetData()
{
foreach (var data in Model.Plan.Points)
{
yield return data;
}
foreach (var data in Model.Plan.Points)
{
yield return data;
}
}