Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement in C# and "a constant value is expected"

Tags:

Why does the compiler say "a constant value is required" for the first case...the second case works fine...

switch (definingGroup)
{
    case Properties.Settings.Default.OU_HomeOffice:  
        //do something  
        break;
    case "OU=Home Office":  
        //do something
        break;
    default:
        break;
 }

also tried...

switch (definingGroup)
{
    case Properties.Settings.Default.OU_HomeOffice.ToString():  
        //do something
        break;
    case "OU=Home Office":
        //do something
        break;
    default:
        break;
 }

...same error

Here's the Properties.Setting code

[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("OU=Home Office")]
public string OU_HomeOffice {
    get {
        return ((string)(this["OU_HomeOffice"]));
    }
}
like image 393
w4ik Avatar asked Jan 21 '09 19:01

w4ik


People also ask

What is a switch statement in C?

Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier.

What is switch statement in C with example?

Explanation: Switch statement only supports Integral data types, Any other data types will throw an Invalid type error. Other examples for Invalid switch: switch(4.5) , switch(10.0/7.1), switch(a + 4.5) etc. The part of the case clause must be a constant integral value or a constant expression followed by a colon.

What is known as switch statement?

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

What is the syntax of switch statement?

The syntax of the switch statement is: statement(s); break; case constant 2: statement(s);


2 Answers

Properties.Settings.Default.OU_HomeOffice isn't a constant string - something known at compile time. The C# switch statement requires that every case is a compile-time constant.

(Apart from anything else, that's the only way it can know that there won't be any duplicates.)

See section 8.7.2 of the C# 3.0 spec for more details.

like image 148
Jon Skeet Avatar answered Sep 19 '22 14:09

Jon Skeet


This is because the value cannot be determined at compile time (as it is coming out of a configuration setting). You need to supply values that are known at the time the code is compiled (constants).

like image 42
Jim Petkus Avatar answered Sep 18 '22 14:09

Jim Petkus