Is it possible to define an implicit conversion of enums in c#?
something that could achieve this?
public enum MyEnum
{
one = 1, two = 2
}
MyEnum number = MyEnum.one;
long i = number;
If not, why not?
For further discussion and ideas on this, I followed up with how I currently handle this: Improving the C# enum
enums are largely useless for me because of this, OP.
I end up doing pic-related all the time:
the simple solution
classic example problem is the VirtualKey set for detecting keypresses.
problem here is you can't index the array with the enum because it can't implicitly convert enum to ushort (even though we even based the enum on ushort)
in this specific context, enums are obsoleted by the following datastructure . . . .
You can't do implict conversions (except for zero), and you can't write your own instance methods - however, you can probably write your own extension methods:
This doesn't give you a lot, though (compared to just doing an explicit cast).
One of the main times I've seen people want this is for doing
[Flags]
manipulation via generics - i.e. abool IsFlagSet<T>(T value, T flag);
method. Unfortunately, C# 3.0 doesn't support operators on generics, but you can get around this using things like this, which make operators fully available with generics.I adapted Mark's excellent RichEnum generic baseclass.
Fixing
Kudos to Mark for the splendid idea + implementation, here's to you all:
A sample of usage that I ran on mono:
Producing the output
Note: mono 2.6.7 requires an extra explicit cast that is not required when using mono 2.8.2...
You probably could, but not for the enum (you can't add a method to it). You could add an implicit conversion to you own class to allow an enum to be converted to it,
The question would be why?
In general .Net avoids (and you should too) any implicit conversion where data can be lost.
There is a solution. Consider the following:
The above offers implicit conversion:
This is a fair bit more work than declaring a normal enum (though you can refactor some of the above into a common generic base class). You can go even further by having the base class implement IComparable & IEquatable, as well as adding methods to return the value of DescriptionAttributes, declared names, etc, etc.
I wrote a base class (RichEnum<>) to handle most fo the grunt work, which eases the above declaration of enums down to:
The base class (RichEnum) is listed below.
I found even easier solution taken from here https://codereview.stackexchange.com/questions/7566/enum-vs-int-wrapper-struct I pasted the code below from that link just in case it does not work in the future.