Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associating Additional Information with .NET Enum

Tags:

My question is best illustrated with an example.

Suppose I have the enum:

public enum ArrowDirection {     North,     South,     East,     West } 

I want to associate the unit vector corresponding to each direction with that direction. For example I want something that will return (0, 1) for North, (-1, 0) for West, etc. I know in Java you could declare a method inside the enum which could provide that functionality.

My current solution is to have a static method -- inside the class that defines the enum -- that returns a vector corresponding to the passed in ArrowDirection (the method uses a HashTable to accomplish the lookup but that's not really important). This seems... unclean.

Question:
Is there a best-practice solution for storing additional information corresponding to an enum in .NET?

like image 387
colithium Avatar asked Mar 25 '09 06:03

colithium


People also ask

Can we change enum values in C#?

Enums are compiled as constant static fields, their values are compiled into you assembly, so no, it's not possible to change them. (Their constant values may even be compiled into places where you reference them.)

Can we use string in enum C#?

You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

How do enums work in C#?

In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace. It improves a program's readability, maintainability and reduces complexity.


1 Answers

There's a FANTASTIC new way to do this in C# 3.0. The key is this beautiful fact: Enums can have extension methods! So, here's what you can do:

public enum ArrowDirection {     North,     South,     East,     West }  public static class ArrowDirectionExtensions {      public static UnitVector UnitVector(this ArrowDirection self)      {          // Replace this with a dictionary or whatever you want ... you get the idea          switch(self)          {              case ArrowDirection.North:                  return new UnitVector(0, 1);              case ArrowDirection.South:                  return new UnitVector(0, -1);              case ArrowDirection.East:                  return new UnitVector(1, 0);              case ArrowDirection.West:                  return new UnitVector(-1, 0);              default:                  return null;          }      } } 

Now, you can do this:

var unitVector = ArrowDirection.North.UnitVector(); 

Sweet! I only found this out about a month ago, but it is a very nice consequence of the new C# 3.0 features.

Here's another example on my blog.

like image 128
Charlie Flowers Avatar answered Sep 22 '22 00:09

Charlie Flowers