Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Custom Iterator Implementation

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).

like image 407
Tom Avatar asked Feb 04 '18 08:02

Tom


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

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..

like image 52
rahulaga_dev Avatar answered Sep 29 '22 23:09

rahulaga_dev