I want to get an enum as an int, but only if it has an initializer applied to it - so that I know that the value was explicitly defined and isn't just the default value. This is because I am using enums to represent a mapping with defined int codes. Is there a way to do this with enums, or am I going to have to use something else like a dictionary?
Here is an example - I have the following mapping:
Apples = 1, Bananas = 2, Pears = 4, Pineapples = 7
I want to make sure that if the enum is
public enum Fruit
{
Apples,
Bananas,
Pears,
Pineapples
}
that it won't try to get the int value, because a value of 1 in the enum corresponds to Bananas, not Apples, like it should. Let me know if I need to be more clear.
UPDATE:
I use nullable enums to check if the value was set (or an Unknown element), but that's not what I'm asking here. I don't think I'm doing a very good job explaining it so I'll try again.
I want to be able to get an enum that I know nothing about, take the underlying int and then do something with it. The only thing I care about is that the enum was initialized because it tells me that it has actual codes defined on it. I don't mind if it's null. That is one of the things I check for. But if it isn't null, I want to make sure that the int code is explicitly defined. A code of 0 is totally acceptable - even if it means that it is undefined - as long as that is what the original mapping specifies.
ANOTHER UPDATE:
I got this term 'initialized' from the Microsoft documentation and I think it is causing confusion. What I meant was an enum that has the value of the underlying ints explicitly defined on it. I.e.,
public enum MyEnum
{
One = 1,
Two = 2,
Three = 3
}
as opposed to one that doesn't. I.e.,
public enum MyEnum
{
One,
Two,
Three
}
I think it was also causing confusion that I was referring to these as having the default value set, which is easy to confuse with non-nullable enums that have the first element set by default.
The way that I'm using this is that I have a method that uses reflection to get the value of properties that have certain custom attributes on them. For my purposes, I only want to get the value from enums that have codes explicitly defined on them. Otherwise I can't assume that the int value has any business meaning.