Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are ranges possible with enums?

Tags:

c#

enums

In C#, can you use number ranges in enum types, for example

public enum BookType
{
    Novel = 1,
    Journal = 2,
    Reference = 3,
    TextBook = 4 .. 10
}

EDIT: The reason this is needed is to cast from a number to the enum type, eg:

int iBook = 5
BookType btBook = (BookType)ibook
Debug.Print "Book " + ibook + " is a " btBook

and the expected output is: Book 5 is a TextBook

like image 804
CJ7 Avatar asked May 06 '10 04:05

CJ7


People also ask

What is the range of enum in C?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

Can we have multiple values for enum?

The Enum constructor can accept multiple values.

Can enums have user defined methods?

Below code uses enums with defined methods: We should define methods as abstract methods and then we have to implement defferent flavours/logic based on each enum members. Because of declaring abstract method at the enum level; all of the enum members require to implement the method.

Can enums have fields?

The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.


2 Answers

As others have said, no it isn't possible. It is possible to combine enum values if they are flags:

[Flags]
public enum BookType
{
    Novel = 0,
    Journal = 1 << 0,
    Reference = 1 << 1,
    TextBook1 = 1 << 2,
    TextBook2 = 1 << 3,
    TextBook3 = 1 << 4,
    TextBook4 = 1 << 5,
    TextBook5 = 1 << 6,
    TextBooks1To5 = TextBook1 | TextBook2 | TextBook3 | TextBook4 | TextBook5
}
like image 125
Gabe Moothart Avatar answered Nov 13 '22 06:11

Gabe Moothart


According to the C# standard (p612, The C# Programming Language) the value given to an enumeration must be a constant integer (or any similar type - long, byte, sbyte, short, etc), so a range of values isn't valid.

My compiler (VS2008) agrees with the spec.

Since you can't repeat names within an enumeration, the closest you'll get is something like this:

public enum BookType
{
    Novel = 1,
    Journal = 2,
    Reference = 3,
    TextBook4 = 4,
    TextBook5 = 5, ...
    TextBook10 = 10
}

Which is actually pretty ugly. Perhaps an enum is not the solution to your particular problem ...

like image 26
Bevan Avatar answered Nov 13 '22 06:11

Bevan