A simple question about Enums

internal enum eCoinType { g = 0, h = 1, s = 2 } 

I saw this line in the same code:

 eCoinType coin = new eCoinType(); 

What does it mean?
What does the "new" declaration in Enum do? Thanks

+4
source share
3 answers

Creates an eCoinType instance with a default value of 0, which corresponds to eCoinType.g . The default constructor is the System.Enum class.

Note that although the new keyword is used, you still create an element of the value type, since enumerations are value types, not reference types. This is similar to instantiating a structure using new .

+6
source

To add to what @BoltClock said, it will create an eCoinType with a default value that is 0 in the case of the numeric types that enum comes from. Thus, this will be equivalent to:

 // These all mean the same thing eCoinType coin = eCoinType.g; // <-- This one is preferred, though eCoinType coin = new eCoinType(); eCoinType coin = default(eCointType); eCoinType coin = (eCoinType)0; 
+1
source

This is a bad attitude. I had programmers using this default constructor for enums, which basically assigns the first enumeration value, while programmers really needed a typed first enumeration value. Keep in mind that some people add values ​​to existing enumerations without worrying about the order, and if they put a new value at the top, you get undefined behavior in the code written like this.

 eCoinType cointype = new eCoinType(); 

in this case equals

 eCoinType cointype = eCoinType.g; 

But if you change eCoinType and put something before g, you have changed the application logic.

Mybe has a utility for this (modify the application logic using the enumerations declared in different modules of the module?), But it is as complicated as the Shadows overload keyword in Visual Basic :)

0
source

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


All Articles