Click here to Skip to main content
15,868,133 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Passing Enum type as a parameter

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
30 Aug 2011CPOL 9.5K   1
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 :) :

C#
/// <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;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
General[edit] fixed formatting Pin
Indivara29-Aug-11 17:27
professionalIndivara29-Aug-11 17:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.