M Taher
M Taher

Reputation: 130

assign enum in switch case in c#

I need to change my Enum in switch case statement like below

var en; 
switch (RequestTypID.ToString())
            {
                case "15":
                    en = enum1;
                    break;
                case "16":
                    en = enum2;
                    break;
                case "14":
                    en = enum3;
                    break;
                case "13":
                    en = enum4;
                    break;
                default:
                    break;
            }

and then pas it to a foreach loop like this

foreach (var status in Enum.GetValues(typeof(en)))

i`m geeting an error that says en must be initialize ? what type should i declare for en variable ? what type should i declare for status variable ?

alright i`ve added this line to the code and one problem is solved;

var en = typeof(enum1);

but now it say it cant find en reference in my for each loop ?

i also change my switch case to something like this

switch (RequestTypID.ToString())
            {
                case "15":
                    en = typeof(enum1);
                    break; 
                    ....

Upvotes: 0

Views: 427

Answers (4)

Gian Paolo
Gian Paolo

Reputation: 4249

Enum.GetValues require a Type as parameter. So simply declare you en as Type.

Type en = null;

you cannot declare it as var without initializing it: compiler need to know what is the real type you want to use.

also, you have to change in your switch:

en = typeof(SomeEnum);

Upvotes: 1

Ahmed Magdy
Ahmed Magdy

Reputation: 6030

You have to have another variable to the right side of the var statement so the compile know what to expect.

You should do the following:

var en = YourEnum.Option1;

or

YourEnum en;

Upvotes: 1

Christos
Christos

Reputation: 53958

i`m geeting an error that says en must be initialize ?

This is reasonable, because this var en; is not correct. When we want to declare something implicitly, we have to assign a value to it, when we declare it, in order the compiler infer it's type.

For instance, var n = 4;. The 4 can be stored to a variable of type int. Hence the compiler, when see this declaration understands that the tyoe of n int.

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68655

You can't create an variable with var(var isn't a type) and not assign a value to it.Var means that compiler will evaluate it's type seeing it's value, but here you don't have a value of the variable.So you need to assign a value to your variable en.Assign a value which type is enum1, enum2, enum3, enum4..

Upvotes: 1

Related Questions