How can I make this IEnumerable class?

Hi Experts,

I'm not fully getting this IEnumerable<T> thing.  Please give me some pointers.

First off - the code below is for a list of strings, but I just did that because it takes focus off any specific class I have.

I like having my own GetFirst/GetNext functions - but now I have no choice but to get into iterators with xaml.. But still want to mix the two (if possible).  I understand that the GetEnumerator is the one that is used by loops as an automatic GetFirst/GetNext.

I don't understand the "Collections.IEnumerable.GetEnumerator" one though....  Why are there 2 types?

So my question is - can you please point out - with the example class I have below, what could I do with the "Collections.IEnumerable.GetEnumerator" function - where would I use it?  And is there any way to use the GetNextWord() function in collaboration or as an alternative to what we get with GetEnumerator() in order to implement it?

Here's the simple class we can talk about:
public class MyStringList: IEnumerable<String>
{
	private List<String> m_Strings new List<String>();

	public MyStringList()
	{
		m_Strings.Add("truck");
		m_Strings.Add("Car");
		m_Strings.Add("cat");
		m_Strings.Add("cab");
		m_Strings.Add("bat");
	}

	public IEnumerator<String> GetEnumerator()
	{
		return m_Strings.GetEnumerator();
	}

	System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
	{
		return this.GetEnumerator();
	}

	public String GetNextString()
	{
		return null;
	}
}

Open in new window

LVL 1
threadyAsked:
Who is Participating?
 
it_saigeDeveloperCommented:
Something like:
using System;
using System.Collections;
using System.Collections.Generic;

namespace EE_Q28641100
{
	class Program
	{
		static void Main(string[] args)
		{
			MyStringList strings = new MyStringList();
			foreach (var item in strings)
				Console.WriteLine(item);
			Console.ReadLine();
		}
	}

	public class MyStringList : IEnumerable<String>
	{
		private List<String> m_Strings = new List<String>();
		public MyStringList()
		{
			m_Strings.Add("truck");
			m_Strings.Add("Car");
			m_Strings.Add("cat");
			m_Strings.Add("cab");
			m_Strings.Add("bat");
		}

		public IEnumerator<string> GetEnumerator()
		{
			foreach (string t in m_Strings)
			{
				if (t == null)
					break;

				yield return t;
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public String GetNextString()
		{
			return null;
		}
	}
}

Open in new window

Produces the following output -Capture.JPGThis will explain, in more details, the basics: http://www.codeproject.com/Tips/359873/Csharp-Iterator-Pattern-demystified

-saige-
0
 
threadyAuthor Commented:
thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.