Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I cast an int into a C# enum type?

Tags:

c#

.net

enums

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
}
like image 794
Pavan Josyula Avatar asked Dec 07 '22 14:12

Pavan Josyula


1 Answers

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:

  • Readability
  • Correctness when you don't explicitly cast
  • Ability to access values via reflection etc

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:

  • You can't make them non-nullable
  • You can't switch on them
  • You can't use them for constant values (such as optional parameter defaults)
  • The value will always be a reference, which can impact on memory usage (compared with an enum with an underlying type of byte, for example)
  • Preserving the restricted values in the face of serialization is interesting

On the other hand, such types can act polymorphically and have more information than plain enums, which can be useful.

like image 101
Jon Skeet Avatar answered Dec 29 '22 12:12

Jon Skeet