Quick tricks with C# enums

I’ve mentioned that in these C# tips posts, I’m assuming readers of these posts will know about Java. In a rare bit of tips, I’m going to talk about a C# feature that feels like a downgrade from Java. Let’s talk about enumerations.

In its most minimal implementation, writing C#’s enumerations are pretty simple:

Like Java’s enumerations, C#’s enumerations are useful for variables with a limited number of possible values, especially when they’re better represented in words such as categories, genres, and day of the week. They can be used in switch, and comparisons are pretty easily.

Java’s enumerations, however, are static objects, while C#’s are just sugar coating to integers. This means that while C#’s enumeration variables can represent any integer number, they cannot hold other information such as strings and doubles like Java can, let alone more than one variable (not without hacks, anyway). Despite this, there are some neat tricks available. Let’s start with the obvious one: converting an enumeration to an integer and back:

You can also customize each representation of an enumeration directly.

But perhaps the most interesting feature in enumerations is the ability to change what it’s sugar coating. For example, since most enumeration declarations has less than 256 unique values and no customization in what each value represent, you can save some memory by declaring one as a byte (an integer-like type representing values from 0 to 255):

This feature is greatly useful for use with bit-operations, and customizing how many flags are supported in an enumeration. Advanced programmers can store a list of unique flags like a HashSet without actually declaring one. In the example below, rather than using an int (which is the same as SInt32) that can only represent up to 32 unique flags, we’ve changed the enumeration to a UInt64 so that it can represent up to 64 unique flags.

Happy coding!

Edit: replaced enumerators with enumeration, to avoid confusion with IEnumerators.

No Comments

Have something to say? Leave a comment!

We use cookies to ensure that we give you the best experience on our website.