Eiver Eiver - 1 month ago 4
C# Question

How to refresh switch statement cases automatically in Visual Studio?

I have previously generated a switch statement over an enum using the automatic snippet included in VS 2010 (I pressed sw [tab] [tab]). Later I extended the enum type. It now contains more values. Now I want to update the switch statement, so that it again includes cases for all possible enum values. Is it possible to automatically generate all missing cases for the enum while keeping existing ones, rather than doing that manually?

Answer

As far as I can see there is no way to do that. Not even with Resharper. Your best bet would be to use find in files to locate all instances of a switch statement containing that enum.

Example: if your enum was called Bob, then the generated switch statement probably looks like this:

        switch (someValue)
        {
            case Bob.one:
                break;
            case Bob.two:
                break;
            case Bob.three:
                break;
            default:
                throw new ArgumentOutOfRangeException();
        }

So in this case you could do a Find In Files for "case Bob." and then manually add a case for the new item.


Edit:
@RichieHindle's suggestion is quite cool. Basically do a regex Replace In Files to append your new case to an existing one. In the example above, say you wanted to add a new item to Bob called zero, you'd do a regex Replace In Files for case Bob\.one: with:

case Bob\.zero:\nthrow new NotImplementedException\(\);\ncase Bob\.one:

(might have to mess around with the regex, but that should give you a good start)

Comments