Shantanu Gupta
Shantanu Gupta

Reputation: 21188

how enum is used in .NET

How does enum work in .NET ? eg.

Enum eOpenMode
    Add = 1
    Edit = 2
End Enum

If LOpenMode = eOpenMode.Add Then
    rdoAddProject.Checked = True
ElseIf LOpenMode = eOpenMode.Edit Then
    rdoEditProject.Checked = True

How does this gets compared by their value(1,2) or by its name (add,edit) and what will be memory allocation scheme ?

Upvotes: 1

Views: 501

Answers (4)

Paul Turner
Paul Turner

Reputation: 39615

Enums are essentially a thin layer over a primitive numeric type (by default Int32). Internally they are handled exactly like numeric values and they can be cast to and from their underlying type readily.

Because of this, it's worth noting that when dealing with Enums you have to be careful around handling the values you are passed.

Enum eOpenMode
    Add = 1
    Edit = 2
End Enum

Dim myEnumVal as eOpenMode
myEnumVal = Cast(100, eOpenMode)

This code compiles and runs fine and myEnumVal will contain a value of 100, which is not mapped to a known enumerated value. It would then be legal for me to pass this value to a method expecting an eOpenMode argument, even though it is not one of the enumerated values.

Be sure to check enum values using Switch statements and throw ArgumentOutOfRangeException if the value supplied is not defined in the enumeration.

In addition to this, because enums are backed by numeric types, they can also be utilized as bit-masks to allow a combination of values:

<Flags>
Enum eOpenMode
    Add = 1  
    Edit = 2 
    AddEdit = Add OR Edit
End Enum

Upvotes: 3

mvonballmo
mvonballmo

Reputation: 81

In C#, you use an enum for two purposes:

  1. To constrain the set of available values
  2. To give useful names to those values

If you only had to satisfy part (2), you could just use constants. The storage type for an enum is, by default, Int32. That means that the == operator compares integers. You can control the base type for an enum by specifying the base type explicitly (e.g. Int64 or byte).

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062550

Enums are really just integers - (typically int) - and are compared exactly as such. If you have:

enum Mwahaha {
    Evil = 1, Nasty = 1
}

Then you'll find that Mwahaha.Evil == Mwahaha.Nasty. The only times the names matter are:

  • in your code
  • when using Enum.Parse (etc)
  • when displaying it via ToString() etc (I suspect it is undefined whether Evil or Nasty is displayed above)
  • when using things like xml serialization (similar to the above)

Upvotes: 4

LorenVS
LorenVS

Reputation: 12857

By Default, Enums are based of the Int32 type (although they can be used with other primitive numeric types), so the comparisons are being done on the integer values.

As far as memory representation of the value, It should be identical to a standard Int32 value.

Upvotes: 6

Related Questions