I have an enum and i want to "hide" one of its values (as i add it for future support). The code is written in C#.
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
Reserved
}
I don't want to allow peoples who use this code to use this values (MyEnum.Reserved). Any idea? TIA
You could use the 'Obsolete' attribute - semantically incorrect, but it will do what you want:
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
[Obsolete("Do not use this", true)]
Reserved
}
Anyone who tries to compile using the Foo.Reserved
item will get an error
If you don't want to show it, then don't include it:
public enum MyEnum
{
ValueA = 0,
ValueB = 1,
}
Note that a user of this enum can still assign any integer value to a variable declared as MyEnum:
MyEnum e = (MyEnum)2; // works!
This means that a method that accepts an enum should always validate this input before using it:
void DoIt(MyEnum e)
{
if (e != MyEnum.ValueA && e != MyEnum.ValueB)
{
throw new ArgumentException();
}
// ...
}
So, just add your value later, when you need it, and modify your methods to accept it then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With