Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use an Enum vs Struct [closed]

Tags:

c#

In our database we have a table called ObjectType. This table simply contains a series of rows with an Id and and ObjectName. In our back-end code, we handle different objects in different ways, so it's often required to refer to the ID of an object for comparisons. These IDs are always the same, and they always map to the same object.

What construct would be better for handling these objects if my methods are expecting an integer value to be passed to them?

When would I use a struct? When would I use an enum?

like image 937
JD Davis Avatar asked Oct 17 '25 13:10

JD Davis


2 Answers

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.

like image 162
Christo S. Christov Avatar answered Oct 20 '25 03:10

Christo S. Christov


struct is not an alternative to enum, it's an alternative to a class. It is just the memory layout which is different in a struct and in a class.

If you don't need to have your code follow and support new entries added to your DB, I would go for enums.

Otherwise, if you need to support new DB entires, I would consider a Dictionary<int, string>

like image 38
Fabio Salvalai Avatar answered Oct 20 '25 02:10

Fabio Salvalai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!