Reputation: 55
I've searched a lot but couldn't find how to delete and add values from/to enum in .NET
Let's say we have enum like this:
Public Enum Coordinates
x
y
z
End Enum
What I need is the enum to become like this:
Public Enum Coordinates
x
y
End Enum
Any help will be appreciated.
Upvotes: 0
Views: 3890
Reputation: 18013
If you have heard something about "turning some values in enums on and off", then it must have been about flags enums. Which means, you can do the following:
[Flags]
public enum Coordinates
{
None = 0;
X = 1; // binary 001
Y = 2; // binary 010
Z = 4; // binary 100
}
Now you can use it like this:
Coordinates enabledCoordinates = Coordinates.X | Coordinates.Y; // binary 011
Console.WriteLine(enabledCoordinates); // displays: X, Y (without Flags, it would display 3)
And then adding and removing can be performed by binary AND and OR operations:
// Adding Z coordinate: by binary OR
enabledCoordinates |= Coordinates.Z;
// Removing Z coordinate: by binary AND of the negated Z
enabledCoordinates &= ~Coordinates.Z;
Checking if a coordinate is added can be performed by binary AND:
// checking if Z flag is set
if ((enabledCoordinates & Coordinates.Z) != Coordinates.None)
Console.WriteLine("Z is turned on");
Upvotes: 2
Reputation: 6580
It is not possible (and not the intend) to modify Enumerations at runtime, you should definitly use the correct data structure for this. E.g. like Dimitry suggested an Dictionary<Key, Value>
Upvotes: 4