0

I have a switch block and it is not behaving as I would expect it to. As I've looked through similar questions on this forum, the answers don't directly address my issue, but seem to confirm my thinking. Please tell me where I'm going wrong. Also, I know I can accomplish this another, and probably better way, but that's not what I'm asking. I want to know where my understanding of fall-through is faulty.

  switch (ncPointType)
        {
            case "MSD":
                adjustDisabled = LastToken(initLine, adjustDisabled);//fall through intentional
            case "MSI":
            case "BI":
                latchingPoint = FirstToken(initLine, latchingPoint);
                break;

Now, per my understanding, if ncPointType == "MSD", adjustDisabled and latchingPoint should set. If "MSI", latchingPoint should be set. But the compiler flags the first "case" with the error "Control cannot fall through from one case label ('case "MSD":') to another. Why is this code not valid?

MatthewHagemann
  • 1,167
  • 2
  • 9
  • 20

1 Answers1

3

In C# you must explicitly leave the case section in question. You can use goto case "MSI"; in the end of the first section.

Of course a section of a switch block can also end with break, return, throw, an infinite loop (that the C# compiler can determine is infinite) and so on.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • Thank you for actually reading my question, as some of the other answers clearly did not. Your answer works, but why do you need to use goto in case "MSD" and not case "MSI"? I understand there is a statement under "MSD", but i thought it would continue falling through without a problem after the statement. It just doesn't make sense to me. – MatthewHagemann May 20 '14 at 17:00
  • You should read this: http://msdn.microsoft.com/en-us/library/aa664749%28v=vs.71%29.aspx Especially the section that starts with "Multiple labels are permitted in a switch-section". – LVBen May 20 '14 at 17:02
  • @user3642601 In C#, one single `switch` section can have several labels. Your example has only two "sections". The "labels" `case "MSI"` and `case "BI"` belong to the same section. Having multiple labels of one section is not considered fall-through. Fall-through is not allowed. – Jeppe Stig Nielsen May 20 '14 at 17:09