I have a set of items that have information on them. These items are defined by me, the programmer, and the user do not ever need to change them, they will never need to change based on configuration, and the only time they might change is in a future version of my application. I know before hand how many of these items there should be, and what their exact data is.
An enum, is a great programming construct that let's me predefine a group of keys available in my application and group them under a logical Type.
What I need now, is a construct that let's me predefine a group of keys that have extra information attached to them.
Example:
This is a standard enum:
public enum PossibleKeys
{
Key1,
Key2,
Key3
}
This is the enum I would need:
public enum PossibleItems
{
Item1
{
Name = "My first item",
Description = "The first of my possible items."
},
Item2
{
Name = "My second item",
Description = "The second of my possible items."
},
Item3
{
Name = "My third item",
Description = "The third of my possible items."
}
}
I know this kind of enum does not exist. What I'm asking is: How can I, in C#, hard code a set of predefined items whose data is set in code? What would be the best way to do this?
EDIT: I don't necessarily want a solution that uses enums, just a solution that allows me to have this behaviour, which is to know all possible items in my application, and the info that each of them has.
EDIT 2: It's important for me to be able to get all existing items at runtime. So being able to query all items and to iterate over them is required. Just like I could with an enum.
C# isn't great at this - enums tend to be just that, not so much additional stuff. You can get close with the following, but I'd sooner recommend a class with a private constructor and readonly instances of itself.
Or a non-enum based approched might be something akin to
I agree with that your should probably be using some sort of class. But you could also add an extension method if you really want to use Enums.
then you can Just call Key1.GetPossibleItem();
Another alternative can be using Java style enums
try this
Then for accessing in an iterative fashion you can do
If you want an item with a particular name you could even add this code to your PossibleItems class
P.S. I get extra points for typing this out on a smartphone
If it's purely for description you can use the built-in
DescriptionAttribute
as stated in some of the other answers. If you need functionality that an attribute can't supply, however, you can create a lookup with some sort of metadata object.Something like this:
Then to retrieve:
Note that I'd only use this if there was something attributes couldn't handle. If it's all primitive types you can also simply make your own custom attribute. You're not limited to simply the built-in ones.
Your own custom attribute would end up like:
Then in use: