I have an enum (of underlying type int
) with two values, and a method that takes a parameter of that type. Is it possible to cast any int value to my enum type and pass it to the method? If so, what is the advantage of an enum? Isn't it supposed to restrict the choice of values available?
class Program
{
public void Greeting(MyCode code)
{
Console.WriteLine(code);
}
static void Main(string[] args)
{
var p = new Program();
var m = new MyCode();
m = (MyCode) 3;
p.Greeting(m);
}
}
public enum MyCode:int
{
Hello =1,
Hai
}
Yes, you can cast any value of the underlying type. The enum type is not a restrictive type in that sense.
The advantages of using enums are:
I agree that a more type would be useful too, but it doesn't exist in C#. You can build your own class-based "pseudo-enums" in C# which allow for a restricted set of values (using a private constructor), but:
On the other hand, such types can act polymorphically and have more information than plain enums, which can be useful.
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