I am having trouble understanding some syntax and inner workings of C#. I have a class with a read-only property Bars set in the constructor.
If I do that using the InitializeWithYield
method that yield returns
something, the method is not called fom the constructor. It is instead called every time(!) the property is called. Not what I expected.
If I do it it using a 'plain' method, it works as I expected: initialize the property once and be done.
Clearly, I am not fully understanding the use of yield
. My question is: why is the InitializeWithYield
method not called from the constructor, but every time the property is called?
class Foo
{
public Foo(int length)
{
// toggle these to see the issue
Bars = InitializeWithYield(length);
//Bars = InitializeCalledFromConstructor(length);
}
public void DoSomething()
{
IBar firstBar = Bars.FirstOrDefault(); // calls InitializeWithYield if in constructor
IList<IBar> listOfBar = Bars.ToList(); // calls InitializeWithYield if in constructor
Console.Write($"First Bar has value {b.Value}");
}
IEnumerable<IBar> Bars { get; }
// shorter syntax, but gets called every time the Bars property is used
// also, not called from constructor
IEnumerable<IBar> InitializeWithYield(int number)
{
for (int i = 0; i < number; i++)
{
yield return new Bar(i);
}
}
// this only gets called from the constructor, which is what I want
IEnumerable<IBar> InitializeCalledFromConstructor(int number)
{
IList<IBar> result = new List<IBar>();
for (int i = 0; i < number; i++)
{
result.Add(new Bar(i));
}
return result;
}
}