Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will enums in C# be able to hold undefined values indefinitely?

Given this enum:

enum Numbers 
{
    One = 1, Two, Three
}

And then this code:

var thousandAndTwo = Numbers.Two + 1000;
Console.WriteLine(thousandAndTwo);

Will display 1002 on the console. I know this is expected behavior, but am wondering: can I actually rely on this to always work, and keep working with subsequent versions of C#?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My reason for asking this: I have an enum that indicates the type of a certain kind of message that has a generic structure. Its type indicates what the generic data actually means. All message types used to be known, but now, there is the need for a more dynamic approach, where message types can vary and fall outside of scope of the defined values for the enumeration.

>Solution :

For the current version of language the Enum may have any value of underlying type: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/enums#186-enum-values-and-operations

The set of values of the enum type is the same as the set of values of the underlying type and is not restricted to the values of the named constants.

I can’t predict future, but my opinion is that MS unlikely will heavily change this behaviour.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading