views:

4619

answers:

3

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"]));
    }
}

Thanks,
Greg

+14  A: 

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.

Jon Skeet
Jon - tell me you didn't come up with "section 8.7.2 of the C# 3.0 spec" off the top of your head. Sheesh...and you had the first answer as well.
Mark Brittingham
Borderline sad... :)
Brian Rudolph
No, don't worry - I did have to look it up. That was actually in an edit, too - but I suspect SO doesn't bother showing it as an edit if it's close enough to the original post.
Jon Skeet
+6  A: 

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).

Jim Petkus
+3  A: 

What it's basically saying is that it needs to ensure that the value for each case will not change at runtime. Hard-coding your string in-line like you did on the second case will ensure that the value won't change at run time (as would declaring a 'const' variable and assigning it the hard-coded string as a value).

The first case is making a call into a property of a class, the value of which isn't known to the compiler at compile time.

If you have some 'configuration' values that are pretty much doing to be constant within your application, you might consider creating a class where you can hard-code these values are const variables and use those in your switch statements. Otherwise, you're likely going to be stuck with having to use if/else if statements.

Jesse Taber