0

I'm a Java developer, making a transition to working in C#. I'm familiar with the following pattern -- abstract method or interface implemented by each Enum member -- in Java:

public enum Animal {
    CAT {
        public String makeNoise() { return "meow!"; }
    },
    DOG {
        public String makeNoise() { return "woof!"; }
    };

    public abstract String makeNoise();
}

and I am wondering if (a) this pattern is possible in C# and (b) whether this is a Csharpy (do people say that?) thing to do. (I don't have my ide setup yet, and concede I should be able to try this out on my own. But it is interesting that I have had a hard time finding an example of this pattern for C# on the internet). Thanks!

  • 1
    You can't add methods to C# enums at all. They are "simply" an association of names to numeric values (and a few conversion rules to try to avoid silly mistakes in using them) – Damien_The_Unbeliever Apr 06 '21 at 07:05
  • Use extension methods. – Theraot Apr 06 '21 at 07:07
  • A: Nope, sadly not. You can however use [extension methods](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) as described in [this](https://stackoverflow.com/a/5985710/9363973) answer. B: Nope, as it is not possible, this isn't "Csharpy", or "idiomatic" C# what most people call it, the idiomatic way of doing this is by using extension methods – MindSwipe Apr 06 '21 at 07:08
  • @theraot yeah, I guess that link does address this question. Thanks! – Rumpertumskin79 Apr 06 '21 at 07:12

0 Answers0