Suppose I have a class and an interface like this:
public interface IClassA
{
IEnumerable<object> MyStuff { get; }
}
public class ClassA : IClassA
{
public List<object> MyStuffList { get; set; }
public IEnumerable<object> MyStuff { get { return MyStuffList.AsEnumerable(); } }
}
Now if later on, I have some instance of ClassA wrapped in an IClassA somewhere, and I want to do a foreach on IClassA's MyStuff:
public void DoStuff(IClassA param)
{
foreach(var x in param.MyStuff)
{
Debug.WriteLine(x.ToString());
}
}
Does MyStuffList.AsEnumerable() get called on each iteration of the loop, or does this get resolved only once at the beginning of the loop? My instincts tell me that it is the latter, as re-calling .AsEnumerable would invalidate the foreach loop's enumerator/iterator/whatever. Basically, I just want to be able to expose a strictly read-only collection through an interface, and be able to manipulate the collection behind the scenes where appropriate. Is this a decent way to do it?