1

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?

Jakotheshadows
  • 1,485
  • 2
  • 13
  • 24
  • why don't you put a breakpoint in your getter and see? – Sam I am says Reinstate Monica Jul 18 '14 at 16:07
  • I guess my search criteria was too specific to get to that question/answer. Thanks for pointing me in the right direction Sriram Sakthivel! – Jakotheshadows Jul 18 '14 at 16:12
  • as side note I'd say that [`List.AsReadOnly`](http://msdn.microsoft.com/en-us/library/e78dcd75%28v=vs.110%29.aspx) it's probably better in this case, since it explicitly marks your collection as read-only. If you are using .NET 4.5 you can use the new [`IReadOnlyCollection`](http://msdn.microsoft.com/en-us/library/hh881542%28v=vs.110%29.aspx) interface. – Paolo Moretti Jul 18 '14 at 16:14

0 Answers0