65.9K
CodeProject is changing. Read more.
Home

Passing Enum type as a parameter

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Aug 30, 2011

CPOL
viewsIcon

9940

Seeing as I "researched" your code and the code on StackOverflow for my own implementations, I figure I should post this - It's a default enumerator for any Enum. Free to use, free to copy; just attribute alike :) : /// /// Created based on the "Passing Enum type...

Seeing as I "researched" your code and the code on StackOverflow for my own implementations, I figure I should post this - It's a default enumerator for any Enum. Free to use, free to copy; just attribute alike :) :
        /// <summary>
        /// Created based on the "Passing Enum type as a parameter" CodeProject article
        /// and "Create" Generic method constraining T to an Enum question on StackOverflow.
        /// Code is completely author-written, despite any similiarities and adds to the ideas presented there.
        /// </summary>
        /// <typeparam name="T">The type of Enum.</typeparam>
        public class EnumEnumerator<t> : IEnumerable<t>, IEnumerator<t>
            where T : struct, IConvertible
        {
            private Array a;
            private int index;

            public EnumEnumerator()
            {
                var type = typeof(T);
                if (!type.IsEnum) throw new ArgumentException("T is not an Enum.");
                this.a = Enum.GetValues(type);
                this.index = -1;
            }

            public IEnumerator<t> GetEnumerator()
            {
                return new EnumEnumerator<t>();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return new EnumEnumerator<t>();
            }

            public T Current
            {
                get { return (T)a.GetValue(index); }
            }

            public void Dispose()
            {
                
            }

            object System.Collections.IEnumerator.Current
            {
                get { return a.GetValue(index); }
            }

            public bool MoveNext()
            {
                ++index; return index < a.Length;
            }

            public void Reset()
            {
                index = -1;
            }
        }