Omar Alaa Omar Alaa - 2 months ago 11
C# Question

C# How to Make Enum as a switch?

i used to make this enum operations as just as int and give it value like 1, 2, 3 ,4 in the calculator i was trying to make but people told me that i should i make it as enums to be somethings that make sense . now i wanna put the enum value in the switch.

//public Variables
double rat;
string M;
public enum operations {add = 1, sub = 2, mult = 3, div = 4} ;
bool NewText = false;

private void btnmult_Click(object sender, EventArgs e)
{
//Button "*"
operations value = operations.mult;
rat = Convert.ToDouble(result.Text);
label1.Text = rat + " *";
result.Text = "";
}
private void EqualButton_Click(object sender, EventArgs e)
{
switch (operations) // this is the point which is am confused at
{
case (operations.mult): //multiplyication
TheEqualMult(rat);
label1.Text = "";
break;
}
}


now What i should write after the word switch between the () ? what i want to type is the enum value which refers to 1 or 2 or 3 or 4 so the button can know which is right operation to go in.

Answer

The following is what you are looking for.

Note that when declaring enums, values will be automatically assigned incrementally. By default the first value is zero, unless you override it.

In your switch statement you use the variable whose value you are switching on - in your case value.

double rat;
string M;
public enum operations 
{
    add = 1,
    sub,
    mult,
    div
} ;
bool NewText = false;
operations value;

private void btnmult_Click(object sender, EventArgs e)
{
    //Button "*"  
    value = operations.mult;
    rat = Convert.ToDouble(result.Text);
    label1.Text = rat + " *";
    result.Text = "";
    }

private void EqualButton_Click(object sender, EventArgs e)
{

    switch (value) // use a variable at this point
    {            
        case operations.mult: //multiplication
            TheEqualMult(rat);
            label1.Text = "";
            break;
        case operations.add: //addition
            ....
            break;
        case operations.sub: //subtraction
            ....
            break;
        case operations.div: //division
            ....
            break;
        default: //invalid operation
            ....
            break;
    }
}

Note that in the above code value will default to zero - effectively an invalid enum - so you need the default at the end.

Comments