tags:

views:

295

answers:

3

I was wondering if the enum structure type has a limit on its members. I have this very large list of "variables" that I need to store inside an enum or as constants in a class but I finally decided to store them inside a class, however, I'm being a little bit curious about the limit of members of an enum (if any).

So, do enums have a limit on .Net?

+3  A: 

Due to a limit in the PE file format, you probably can't exceed some 100,000,000 values. Maybe more, maybe less, but definitely not a problem.

280Z28
A very good point.
Pavel Minaev
+7  A: 

Yes. The number of members with distinct values is limited by the underlying type of enum - by default this is Int32, so you can get that many different members (2^32 - I find it hard that you will reach that limit), but you can explicitly specify the underlying type like this:

enum Foo : byte { /* can have at most 256 members with distinct values */ }

Of course, you can have as many members as you want if they all have the same value:

enum { A, B = A, C = A, ... }

In either case, there is probably some implementation-defined limit in C# compiler, but I would expect it to be MIN(range-of-Int32, free-memory), rather than a hard limit.

Pavel Minaev
Thank you, I did not know that you could declare the underlying type of an enum.
Gustavo Rubio
+3  A: 

From the C# Language Specification 3.0, 1.10:

An enum type’s storage format and range of possible values are determined by its underlying type.

While I'm not 100% sure I would expect Microsoft C# compiler only allowing non-negative enum values, so if the underlying type is an Int32 (it is, by default) then I would expect about 2^31 possible values, but this is an implementation detail as it is not specified. If you need more than that, you're probably doing something wrong.

DrJokepu
Negative numbers are allowed as long as you don't explicitly specify an unsigned underlying type: Invalid=-1, None=0, OptionA=1, ...
280Z28