When to use an Enum vs Struct

Enumerations aren’t interchangable with structs. They have completely different usages. A struct can have members and methods, but an enumeration can have only labels and values for the labels.

You could use an enum to specify different behaviours of a system

Let’s say you have a class Person and let’s say that for whatsoever reason a person can have an emotional state.

A good implementation would use an enum like this:

enum EmotionalState
{
     Happy = 3,
     Sad,
     Shy    
}

You can use the enum items as integers like this :

int b = (int)EmotionalState.Sad // <---4

and also in the reverse direction

int v = 3;
EmotionalState s = (EmotionalState)v; // Happy

Note that the enum members don’t have type. They could also be assigned a starting value. So for example if you assign 3 on the first item the next item would be marked as 4.

A good example for a struct is a Point

struct Point {
   int a;
   int b;
}

structs should be small as they are value types and are kept on the stack where as reference types are kept on the heap.

Leave a Comment