2

I'm looking for a quick method that will sort existing enum members defined in a switch statement, alphabetically.

I can't seem to find anything to do this, and also not in ReSharper where I would had thought it would had been present if anywhere.

Does anyone know how to achieve this, without doing things manually?

Mooman
  • 31
  • 1

1 Answers1

1

There is a lightbulb tool in VS2017 to add missing cases (the IDE0010), but no sort feature. This "add missing cases" feature follows the order of values in the enum declaration, which is what you'd usually want.

Sorting an existing switch case list in place would be an idea for an extension.

But seriously, why would you really ever need to do this? We usually sort our enum-based switch cases in just the same order they're defined in the enum itself, and if that happens to be alphabetical, fine, otherwise their order may have a functional meaning implied by the author of the enum, and that can be replicated in the switch case order.

If the cases are still empty, you could use a VS extension like this one to sort the enum fields in the declaration, remove all cases, and execute the IDE0010 "add missing cases" tool.

Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
  • the original enum was sorted alphabetically, so that's why I mentioned. Sorting by where they are defined in the enum would be a cool addin - nice idea. – Mooman Sep 15 '18 at 21:27
  • Enum values aren't defined in a switch statement, they are defined in an `enum` declaration. Their order is significant; their associated integer value is assigned by their order (by default). `System.Enum` has a method that will return the values as strings. It would be easy to sort that list. But, no VS doesn't do it for you – Flydog57 Sep 15 '18 at 23:46
  • 2
    @Flydog57 I am quite aware enum values aren't defined in a switch statement. Seems strange no addin for this basic thing to keep them in a sync'd order with original enum declaration. :-( – Mooman Sep 16 '18 at 12:08