Operator Overloading and Enumerations?
Is there any chance that in future versions it will be possible to overload operators for enumerations? I was very skeptical if it was really necessary to introduce this feature to VB. I almost never missed it.
As someone with Pascal background I like speaking numbers, so I often use enumerations.
| |
<Flags()> _ Enum SampleEnum Value1 = 1 Value2 = 2 Value3 = 4 Value4 = 8 EndEnum
|
I would like to write Code in this way:
| |
Dim eas SampleEnum e = SampleEnum.Value1 + SampleEnum.Value4
|
and not:
| |
Dim eas SampleEnum e =CType (SampleEnum.Value1 + SampleEnum.Value4, SampleEnum)
|
It would be much more readable (and shorter to type
)
And don′t tell me to turn Option Strict off
[1737 byte] By [
Ramirez] at [2008-1-21]
Addition of enums as you're doing is only always valid for flags. For more general enums, you run the risk of exceeding the allowable range of values. If you're dealing with flags, you can use the Or operator to combine the enums.
Dim e As SampleEnum
e = SampleEnum.Value1 Or SampleEnum.Value4
Console.WriteLine(e) ' Outputs 9
This syntax is supported in .NET Framework 1.0 and above.
I know that the addition only makes sense for flags enumerations. That′s why I tried to overload the + operator in my enumaration.
The Or notation is quite more readable but works also for non flagged enumerations.
Thx
It looks like unneccessary.
They dont do operator overloading to look more readable.
: )
You can convert your enum with implicit conversion. U have to use operator overloading when u cant convert your variables.
good works