Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you override an enum in C#?

This is my code:

void Main()
{
    StarTrek baseClass = new StarTrek();
    NewGeneration childClass = new NewGeneration();

    baseClass.ShowEnum();
    childClass.ShowEnum();
}

public class StarTrek
{
    internal enum Characters
    {
        Kirk, Spock, Sulu, Scott
    }

    public void ShowEnum()
    {
        Type reflectedEnum = typeof(Characters);
        IEnumerable<string> members = reflectedEnum.GetFields()
                                            .ToList()
                                            .Where(item => item.IsSpecialName == false)
                                            .Select(item => item.Name);
        string.Join(", ", members).Dump();
    }
}

public class NewGeneration : StarTrek
{
    internal new enum Characters
    {
        Picard, Riker, Worf, Geordi
    }       
}

ShowEnum always displays:

Kirk, Spock, Sulu, Scott

even if it was called in the NewGeneration class. Am I missing/misunderstanding something? Is there a way for ShowEnum to use the NewGeneration.Characters instead of StarTrek.Characters?

like image 417
acermate433s Avatar asked Oct 18 '11 13:10

acermate433s


People also ask

Can you override an enum?

By default, the enum value is its method name. You can however override it, for example if you want to store enums as integers in a database, instead of using their method name. An enum value doesn't have to be a string, as you can see in the example.

Can we change value of enum in C?

You can change default values of enum elements during declaration (if necessary).

Can enums be changed?

Enum constants are final but it's variable can still be changed. For example, we can use setPriority() method to change the priority of enum constants. We will see it in usage in below example. Since enum constants are final, we can safely compare them using “==” and equals() methods.


1 Answers

Your second enum is shadowing the first one, in just the same way as declaring a new field within NewGeneration would. Nested types aren't polymorphic - the code in ShowEnum will always refer to StarTrek.Characters; the code is built against that type at compile-time.

It's not really clear what you're trying to do, but you definitely can't do it in the way that you're trying. If you want polymorphic behaviour you have to be using methods, properties or events, which must then be declared virtual in order to be overridden in the derived class.

(It's worth noting that overloading and overriding are different, by the way - your question refers to overloading but I think you meant overriding.)

like image 186
Jon Skeet Avatar answered Sep 27 '22 22:09

Jon Skeet