afaolek
afaolek

Reputation: 8821

enum types in C#

I read this statement in a C# book.

Enumerations do not necessarily need to follow a sequential ordering, and need not have unique values.

If I understand that statement, it means one of this is acceptable (I don't know which):

1.

enum EmpType
{
    Manager = 1,
    Grunt = 1,
    Contractor = 100,
    VicePresident = 9
}

2.

enum EmpType
{
    Manager = 10,
    Manager = 1,
    Contractor = 100,
    VicePresident = 9
}

Can someone please explain to me? I thought C# was supposed to be a subset of C/C++.

Upvotes: 5

Views: 764

Answers (5)

DanNsk
DanNsk

Reputation: 900

Actually - why not to check :) Each enum is subclass of System.Enum class (specially handled), each enum element is a static field initialized with a literal value - you cannot have two fields with the same names, but can have fields with the same values, so #1 will work, #2 won't.

Upvotes: 3

Akram Shahda
Akram Shahda

Reputation: 14781

Refering to enum (C# Reference):

The default underlying type of enumeration elements is int.

You can assign any integer value to any enumuration element. You can assign duplicated values to different elements. However, elements names must be unique.

That means, block one is correct. But, block two is not.

Upvotes: 0

Kamyar
Kamyar

Reputation: 18797

Number 1 is acceptable. Number 2 throws a compile time exception. You can have multiple Equivalent values. But not equivalent duplicate names.

For example, suppose you want to define an enum for a companie's personnel job levels. You have staff, management. staff include sales department and IT department and it doesn't make any difference for you if a person is in sales or IT, He/she is considered staff anyway. You can define the following enum:

public enum PersonnelLevels
{   
    Management=0,
    Sales=1,
    IT=1
}  

Upvotes: 1

Richard Friend
Richard Friend

Reputation: 16018

The first one would be valid, you may have duplicate Values not duplicate Names

Upvotes: 4

mdm
mdm

Reputation: 12630

1 is correct, 2 is not.

As the book says, enums need not have unique values (example 2 shows enums with non-unique names). Names must be unique, as it is how the compiler matches it up to a value.

Upvotes: 3

Related Questions