Thomas
Thomas

Reputation: 5911

Use Class property value for a switch statement

am using generated protobuf code (see http://code.google.com/p/protobuf/)

I have a generated class looks like this :

public class Fruits{
    private int _ID_BANANA = (int)1;
    private int _ID_APPLE  = (int)2;

    public int ID_BANANA
    {
      get { return _ID_BANANA; }
      set { _ID_BANANA = value; }
    }

    public int ID_APPLE
    {
      get { return _ID_APPLE; }
      set { _ID_APPLE = value; }
    }
}

Then they are constant values but I can't use then as such in my code. For example I want to do a mapper like this :

public static Color GetColor(int idFruit) {    
    switch (idFruit)
        {
            case new Fruits().ID_BANANA:
                return Color.Yellow;
            case new Fruits().ID_APPLE:
                return Color.Green; 
            default:
                return Color.White;                 
        }
 }

I have the error : a constant value is expected.

I thougth about creating an enum, but seems to be the wrong way, tryed something like :

public const int AppleId = new Fruits().ID_APPLE;

Not working either... Someone have an idea?

Upvotes: 0

Views: 3086

Answers (2)

Jens Meinecke
Jens Meinecke

Reputation: 2940

The case values in a switch statement have to be constants - that's part of the switch statement's definition:

switch (expression)
{
   case constant-expression:
      statement
      jump-statement
   [default:
       statement
       jump-statement]
 }

as per the switch (C#) documentation from Microsoft.

you will notice the constant-expression bit. That means that it can be determined at compile time. So calls to functions (and a reference to a property property is really a function call in disguise) are not allowed here.

Upvotes: 0

Sergey Metlov
Sergey Metlov

Reputation: 26291

Why not to use if else if statements here?

var fruits = new Fruits();
if (idFruit == fruits._ID_BANANA)
    return Color.Yellow;
else if (idFruit == fruits._ID_APPLE)
    return Color.Green;
else
    return Color.White;

Or dictionary:

this.fruitsColorMap = new Dictionary<int, Color>
    {
        { fruits._ID_BANANA, Color },
        { fruits._ID_APPLE, Green }
    };

And then:

public static Color GetColor(int idFruit) {
    if (this.fruitsColorMap.ContainsKey(idFruit) {
        return this.fruitsColorMap[idFruit];
    }
    return Color.White;
}

Upvotes: 1

Related Questions