Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum value as hidden in C#

Tags:

c#

enums

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

like image 838
Tom Avatar asked Aug 28 '10 18:08

Tom


2 Answers

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

like image 96
Ray Avatar answered Sep 17 '22 14:09

Ray


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.

like image 42
dtb Avatar answered Sep 19 '22 14:09

dtb