-4

I was reading this answer

By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.

I would use Enum.GetValues(typeof(Suit)) instead.

Why? How is GetValues better than iterating?

Community
  • 1
  • 1
adoomedknight
  • 39
  • 1
  • 7

2 Answers2

2

Looks like you misunderstood the context there.

Poster of the answer you are referring to suggests to use GetNames to iterate through names of the enum. But than he says that when it comes to values enumerating over GetValues is better than incrementing.

So one is not better than the other, they serve different purposes well, and author of the answer outlines this.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • _enumerating over GetValues is better than incrementing_. Why? – adoomedknight Apr 20 '15 at 12:21
  • @adoomedknight: Because you can have "holes" in your enum. Conside `enum E { A = 1, B = 2, C = 4 }`. Incrementing will yield `A, B, 3, C`, enumerating over all values will yield `A, B, C` – knittl Apr 20 '15 at 12:24
  • @adoomedknight, to add to what knittl said, enum might be defined with any values. Even with [chars](http://stackoverflow.com/a/10203473/728795). So incrementing might give you a lot of stuff that is no in the enum. `GetValues` is guaranteed to return only relevant values though – Andrei Apr 20 '15 at 12:30
0

As @knittl stated:

Because you can have "holes" in your enum. Consider enum E { A = 1, B = 2, C = 4 }. Incrementing will yield A, B, 3, C enumerating over all values will yield A, B, C

and thanks to @Andrei for pointing out:

enum might be defined with any values. Even with chars. So incrementing might give you a lot of stuff that is no in the enum. GetValues is guaranteed to return only relevant values though

Community
  • 1
  • 1
adoomedknight
  • 39
  • 1
  • 7