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
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.
The Enum constructor can accept multiple values.
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.
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
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
}
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 ...
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