Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use web.config value in switch case in C# without if , else loop "A constant value is expected."

Below is switch case

switch (strID)
{
    case ConfigurationManager.AppSettings["Key1"].ToString():
        Label1.Visible = true;
        break;
    case ConfigurationManager.AppSettings["Key2"].ToString():
        Label2.Visible = true;
        break;
    case ConfigurationManager.AppSettings["Key3"].ToString():
        Label3.Visible = true;
        break;
    default:
        Label1.Visible = true;
        break;
}

But it gives error "A constant value is expected."

I know that you can't have variables in the switch statement.But is any way ?

like image 559
MSTdev Avatar asked Nov 29 '16 07:11

MSTdev


1 Answers

You can use only constant value in case statement.

Better you can use if statement e.g.

if(ConfigurationManager.AppSettings["Key1"].ToString() == strID)
{
   Label1.Visible = true;
}
else if(ConfigurationManager.AppSettings["Key2"].ToString() == strID)
{
   Label2.Visible = true;
}

. . . . . . .

else
{
    //default
}
like image 84
maarif Avatar answered Oct 28 '22 21:10

maarif