7

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 ?

MSTdev
  • 4,507
  • 2
  • 23
  • 40

3 Answers3

3

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
}
maarif
  • 59
  • 5
0

You can have variables in switch's CASE statements. But, that must be a compile time constants i.e. `const' variable.

CASE statements need to be constant; by having them be constant it allows the statement to be much more heavily optimised. Switch will generate the equivalent of a hash table with the case statement values as keys. That approach couldn't be used if the values can change.

Values from ConfigurationManager.AppSettings are decided at run-time. So you can not use it in Switch's CASE statements.

You can use if.. else statements as alternative solution.

See - C# switch statement limitations - why?

Community
  • 1
  • 1
Dhwani
  • 7,484
  • 17
  • 78
  • 139
-1

Assign the 3 values from Web.Config file to 3 different constants like const string key1 = ConfigurationManager.AppSettings["Key1"].ToString() and use them in the cases inside switch instead of giving ConfigurationManager.Appsettings["Key1"].ToString();

Sethu Bala
  • 457
  • 3
  • 17
  • switch statement not support variable also – MSTdev Nov 29 '16 at 07:52
  • No. Don't declare it as a variable, instead declare it as a constant. Please use the code below: const string key1 = ConfigurationManager.AppSettings["Key1"].ToString(); const string key2 = ConfigurationManager.AppSettings["Key2"].ToString(); const string key3 = ConfigurationManager.AppSettings["Key3"].ToString(): switch (strID) {case key1: Label1.Visible = true; break; case key2: Label2.Visible = true; break; case key3: Label3.Visible = true; break; default: Label1.Visible = true; break;} – Sethu Bala Nov 29 '16 at 07:56