IEnumerable to IEnumerable<> wrapper

A simple .net class which maps an IEnumerator to a generic IEnumerator, which is very usefull to convert from generic to non-generic collections.

using System;
using System.Collections;
using System.Collections.Generic;

namespace Intrepid.Collections.Generic
{
	public class EnumerableWrapper<T> : IEnumerable<T>
	{
		class EnumeratorWrapper : IEnumerator<T>
		{
			IEnumerator enumerator;
			
			public EnumeratorWrapper(IEnumerator enumerator)
			{
				this.enumerator = enumerator;
			}
			
			public void Dispose()
			{
				// maybe we should dispose the underlying IEnumerable?
			}
			
			public bool MoveNext()
			{
				return enumerator.MoveNext();
			}
			
			public void Reset()
			{
				enumerator.Reset();
			}
			
			object System.Collections.IEnumerator.Current
			{
				get { return enumerator.Current; }
			}
			
			public T Current
			{
				get { return (T)enumerator.Current; }
			}
		}
		
		IEnumerator enumerator;
		
		public EnumerableWrapper (IEnumerable enumerable)
		{
			enumerator = enumerable.GetEnumerator();	
		}
		
		public IEnumerator<T> GetEnumerator()
		{
			return new EnumeratorWrapper(enumerator);
		}
		
		IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return enumerator;
		}
	}
}

Leave a Reply

Your email address will not be published.