Reputation: 53
I have a class, say Myclass, with a list variable, say string list, which I want to call from outside Myclass object instance, in a loop, succinctly like:
Myclass myclass = new Myclass();
foreach (string s in myclass)
{
}
I suspect it uses the implicit operator keyword inside of Myclass on a property. Syntax grrr..! Any help?
(Not sure if it's good practice but there are times when it comes in handy).
Upvotes: 5
Views: 7950
Reputation: 4164
Foreach basically works on sequence. Your MyClass
need to implement IEnumerable and eventually return IEnumerator implementation via GetEnumerator.
IEnumerator basically provides MoveNext and Current property which your foreach loop uses to query sequence elements one after another.
You can get more info around this by searching around Iterators in C#. Adding short snippet so you can visualize what i meant :
public class MyIterator : IEnumerable<string>
{
List<string> lst = new List<string> { "hi", "hello" };
public IEnumerator<string> GetEnumerator()
{
foreach(var item in lst)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public class Consumer
{
public void SomeMethod()
{
foreach(var item in new MyIterator())
{
}
}
}
Hope this helps..
Upvotes: 11