Can I convert int to C # enum type?

I have an enumeration (of the base type int ) with two values ​​and a method that takes a parameter of this type. Is it possible to pass an int value to my enum type and pass it to a method? If so, what is the advantage of renaming? Shouldn't that limit the choice of available values?

 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 } 
+4
source share
3 answers

Yes, you can specify any value of the base type. An enum type is not a limiting type in this sense.

Benefits of using enumerations:

  • readability
  • Correct when you are not explicitly using
  • Ability to access values ​​through reflection, etc.

I agree that another type will be useful, but it does not exist in C #. You can create your own pseudo-enumerations based on a class in C # that allow a limited set of values ​​(using a private constructor), but:

  • You cannot make them unclean.
  • You cannot turn them on
  • You cannot use them for constant values ​​(e.g. optional default parameters)
  • The value will always be a reference, which may affect memory usage (for example, compared to an enumeration with a basic byte type)
  • Saving limited values ​​in the face of serialization is interesting

On the other hand, such types can act polymorphically and have more information than simple enumerations that may be useful.

+7
source

Just add the answer to Jon: you can always use

 Enum.IsDefined(typeof(MyCode), value) 

To check if the provided value exists in the enumeration definition.

+6
source

In many ways, Enums are implemented as syntactic sugar in .NET languages. We quote

The enum keyword is used to declare an enumeration, a separate type consisting of a set of named constants called a list of enumerators.

In other words, enumeration values ​​are fields, like any other, and not an integral choice of values. There is nothing to prevent you from listing invalid values ​​in an enumeration. The most you can do to force the actual contents of an enumeration to use the static Enum.IsDefined method (although you can define extension methods if your imagination requires it).

However, the purpose of enumerations is not to check user input, so they should not be as strict as this. The purpose of enumerations is to associate a name with a numerical value and easily display a list of possible combinations of this type. And don't forget that their free design allows things like Day.Saturday | Day.Friday Day.Saturday | Day.Friday or more complex couplings. They are still very helpful.

+2
source

Source: https://habr.com/ru/post/1414703/


All Articles