Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement: "a constant value is expected"

Currently I'm fighting with that "magical strings" issue:

public class MyDataField
{
    // class definition
}

// exuecuted method
public void SwitchMultipleDataFields()
{
    var myField = new MyDataField();
    switch(myField.GetType().ToString())
    {
        // only case, which works
        case "MyDataField":
            // case operations
            break;

        // other option:
        case typeof(MyDataField).ToString():
            // case operations
            break;

        // other cases of other FieldTypes
    }
}

Now I get the error Message I've written in the title of my thread. I think the problem is that this string is not a constant while "non-compile-time". So the only possible way to ask switch this is via explicitly determining the value of that case string. My problem just is that I don't get an compile error in case I'd rename the MyDataField class. So 90% of these classes are generic anyway. These are handled in the default of the switch statement. Isn't there another way than explicitly determining the value of the case value?

Please don't argue about the sense of this method. I've just written that to illustrate my problem in an easier way

like image 516
Michael Schnerring Avatar asked Oct 27 '25 08:10

Michael Schnerring


1 Answers

Just use an if:

Type type = myField.GetType();
if (type == MyDataField.GetType())
{
    …
}
else if (type.ToString() == "MyDataField")
{
    …
}
else
{
    …
}

You even don't need to compare type names, but the Type objects (references) directly.

like image 172
Ondrej Tucny Avatar answered Oct 29 '25 21:10

Ondrej Tucny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!