C
C#3y ago
surwren

differentiating use cases- Enum vs Tuple vs Array

What are some common cases where enums are preferable to use over tuples/arrays, and vice versa? If that's too expansive a scope of a question, perhaps what are the respective advantages/disadvantages of each?
11 Replies
Ben
Ben3y ago
I'll start off by reading what each type is. As all 3 do not serve the same purpose at all. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum I'm sure that after reading the doc of each type you'll have a better understanding or a more specific question to follow up with.
surwren
surwrenOP3y ago
Take for example a program where a string cycles between a series of different values (say 9). I could implement the string values to by cycled through using an array (indices 0-8) and a tuple (explicitly naming the indices), and I don't see why an enum couldn't be used to implement it as well. What would be the advantage and disadvantage of using a string/ tuple/enum in that scenario? I legitimately don't understand
Binto86
Binto863y ago
Use array when you need to loop thru some values, use enum if you have some options, use tuples when you are too lazy to create a class and need to use the tuple just once
surwren
surwrenOP3y ago
Thanks!! Very succinct
Thinker
Thinker3y ago
Should also mention that records exists, which are like tuples but they get compiled into classes/structs. (string name, int age, Gender gender) -> record Person(string Name, int Age, Gender Gender);
Becquerel
Becquerel3y ago
Enums are best at representing a small set of closed values: things like directions (up/down/left/right) or days of the week. There's never going to be a new thing in those concepts. The reason why I say this is because adding a new member to an enum usually entails some really boring, error-prone refactoring: they're 'brittle' (If you want to represent different variations of something more general, polymorphism is probably a better choice) The reason why you'd use an enum is if you want to make completely sure you've covered every case for a given problem, because the language/your IDE can warn you if you have a switch statement over an enum but forget one of the options.
Mayor McCheese
Definitely avoid ended enums imho like @Becquerel said.
Ben
Ben3y ago
When would you use records over tuples?
Thinker
Thinker3y ago
Literally always
Becquerel
Becquerel3y ago
When you would normally use a class, but want value-equality semantics and easy immutability
Thinker
Thinker3y ago
In all seriousness, when having several methods which would return the same tuple type, then having a record with a name is way handier than repeating the same tuple type everywhere.
Want results from more Discord servers?
Add your server