kazim
kazim

Reputation: 2191

C#: Passing enum type as argument

I tried to convert enum to a generic List by using the following code

public static List<T> ToList<T>(Type t) where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}

it complied successfully.

and I tried to call the above mentioned method by using the following code

 enum Fruit
    {
        apple = 1,
        orange = 2,
        banana = 3
    };

    private List<Fruit> GetFruitList()
    {
        List<Fruit> allFruits = EnumHelper.ToList(Fruit);
        return allFruits;
    }

resulted in the following error

Compiler Error Message: CS0118: 'default.Fruit' is a 'type' but is used like a 'variable'

So I am sure how to pass Enum type as a argument.

Upvotes: 1

Views: 4248

Answers (6)

John xyz
John xyz

Reputation: 186

why not just do this:

public static List<T> ToList<T>()
{     
    return Enum.GetValues(typeof(T)).Cast<T>().ToList(); 
} 

Upvotes: 4

Bala R
Bala R

Reputation: 108937

List<Fruit> allFruits = EnumHelper.ToList<Fruit>(typeof(Fruit));

Upvotes: 2

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

public static List<T> ToList<T>() where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}

enum Fruit
{
    apple = 1,
    orange = 2,
    banana = 3
};

private List<Fruit> GetFruitList()
{
    List<Fruit> allFruits = EnumHelper.ToList<Fruit>();
    return allFruits;
}

Upvotes: 8

Femaref
Femaref

Reputation: 61427

Use EnumHelper.ToList<Fruit>(typeof(Fruit));. However, you can lose the parameter, declare as EnumHelper.ToList<T>() and use it EnumHelper.ToList<Fruit>().

Upvotes: 1

Fyodor Soikin
Fyodor Soikin

Reputation: 80714

Loose the argument Type t

The type is already being passed as generic parameter, so you don't need a regular argument for the method.

Upvotes: 1

madd0
madd0

Reputation: 9303

In order to pass a Type to your function, you should use the following syntax:

 EnumHelper.ToList(typeof(Fruit));

Upvotes: 0

Related Questions