Reputation: 113365
I read in The Fundamentals of Programming course that the enum
values should be unique, having the following example:
enum color = { red, orange, yellow };
enum fruit = { apple, orange, kiwi}; // error: orange is redefined
int kiwi = 42; // error: kiwi is redefined
I also found the same idea on this question: Two enums have some elements in common, why does this produce an error?
Enum names are in global scope, they need to be unique.
I write C# apps in MonoDevelop on Ubuntu 14.10 and I tried to reproduce this behavior:
using System;
namespace FP
{
class MainClass
{
enum color { red, orange, yellow };
enum fruit { apple, orange, kiwi}; // error: orange is redefined
int kiwi = 42; // error: kiwi is redefined
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
}
}
}
The program above compiled successfully.
Is this a known MonoDevelop behavior or why it was compiled without errors? Should the Enum values be unique in the global scope?
Upvotes: 3
Views: 1272
Reputation: 700322
No, it's not a bug, that is how C# is supposed to work. The question that you linked to is about C, not C#.
In C all enum values have to be unique, as you can use the value without specifying which enum it belongs to. That's why the example in that question didn't compile.
In C# the enum values only have to be unique within the same enum. In C# you never use an enum value without specifying which enum it belongs to, so values from different enums doesn't conflict.
The enum values will usually be unique, it goes with trying to make identifiers descriptive. If you happen to use the same name for values in different enums, then there is a reason for that. Either the enums are closely related so that they overlap in meaning, or there is a word with more than one meaning.
Upvotes: 3
Reputation: 13799
What you are talking about is behaviour of the c
language.
In c#
enums are not globally accessible by name, you always have to access them by typeName.valueName
, e.g. color.Orange
, fruit.Orange
. So there will be no conflict. In fact many in-built enums use the same value names (StringSplitOptions.None
, CompareOptions.None
).
Upvotes: 6