0

If I have an Enum as follows:

private object myEnumValLock = new object();
private MyEnum _myEnumVal;
public MyEnum MyEnumVal
{
    get
    {
        lock(this.myEnumValLock)
        {
            return this._myEnumVal;
        }
    }
    set
    {
        lock(this.myEnumValLock)
        {
            if (value != this._myEnumVal)
            {
                this.HandleNewMyEnumVal(this._myEnumVal, value);
                this._myEnumVal = value;
            }
        }
    }
}

When using switch case, can I directly use the property like this:

private void MyFunc()
{
    switch (this.MyEnumVal)
    {
        case MyEnum.First:
            // Do Something
            break;
        case MyEnum.Second:
            // Do Something
            break;
    }
}

Or should I read it first and then use switch on the read value like this:

private void MyFunc()
{
    var myEnumVal = this.MyEnumVal;
    switch (myEnumVal)
    {
        case MyEnum.First:
            // Do Something
            break;
        case MyEnum.Second:
            // Do Something
            break;
    }
}

If using if ... else as in this question, I'd need to read the value first. Is it the same case with switch statement? What is the behaviour of the switch statement? Does it read the value at every case statement or reads only once at the beginning?

Xpleria
  • 5,472
  • 5
  • 52
  • 66
  • I would directly use the property. (Unless of course i needed its value somewhere else in my function too and its path and name where really long) – BanForFun May 02 '18 at 13:30
  • @mjwills running on Windows 7/10 - x64/x86. As pointed out in the linked question, for `if ... else` it is necessary to read first. what is the behaviour of the `switch` statement? does it read the value at every `case` statement or reads only once at the beginning? – Xpleria May 02 '18 at 13:35
  • @mjwills How do you say so? In the equivalent `if .. else` example, it is shown that `c` is compared in every single case. – Xpleria May 02 '18 at 13:51
  • Put a breakpoint in your getter. How many times does it get hit? What does that tell you? – mjwills May 02 '18 at 13:53
  • It's a relatively large piece of code until I get there. Nevertheless, I'm on it. – Xpleria May 02 '18 at 13:55
  • @mjwills You're right. It gets hit only once. So I don't need to read it previously. – Xpleria May 02 '18 at 14:04

1 Answers1

0

As @mjwills suggested, I put a breakpoint in the getter and it got hit only once at the beginning of the switch statement. I can't find any specific reference where it says the switch statement reads the value only once (please comment if you find the reference). But the breakpoint does prove it.

So, although you need to have read the value beforehand in case of if ... else, in case of the switch statement, you don't need to.

Xpleria
  • 5,472
  • 5
  • 52
  • 66