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

I've seen this line in the same code:

eCoinType coin = new eCoinType();  

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Mulder
  • 1,913
  • 2
  • 13
  • 7

3 Answers3

6

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

Note that while the keyword new is used, you still create an item of a value type as enums are value types, not reference types. It's similar to creating struct instances with new.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

Just to add to what @BoltClock said, it will create an eCoinType with the default value, which is 0 in the case of numeric types, which enum derives from. So it would be the 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;
Harry Steinhilber
  • 5,219
  • 1
  • 25
  • 23
0

This is a bad attitude. I had programmers using this default constructor for enums which basically assigns the first value of the enum, while programmers actually needed the typed first value of the enum. Mind you some people add values to existing enums not caring about order and if they put the new value at the top, you get undefined behavior in code written like that.

eCoinType cointype = new eCoinType();

in this case equals

eCoinType cointype = eCoinType.g;

But if you modify eCoinType and put something before g, you have altered the application logic.

Mybe there is a usecase for that (modify application logic by using enums declared in different plugin modules?) but that is as much abscure as the Shadows overloading keyword in Visual Basic :)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Marino Šimić
  • 7,318
  • 1
  • 31
  • 61
  • 1
    If numeric values are explicitly defined for each enumerated value, order won't matter. See [this answer](http://stackoverflow.com/questions/4967656/what-is-the-default-value-for-enum-variable/4967673#4967673). – BoltClock Mar 25 '11 at 00:13
  • You are totaly right, i forgot to add that. But numeric values are rarely used though. – Marino Šimić Mar 25 '11 at 00:14