Good day!

In Java, using enums, you can add your own methods to them:

enum Type { INT(true) { public Object parse(String string) { return Integer.valueOf(string); } }, INTEGER(false) { public Object parse(String string) { return Integer.valueOf(string); } }, STRING(false) { public Object parse(String string) { return string; } }; boolean primitive; Type(boolean primitive) { this.primitive = primitive; } public boolean isPrimitive() { return primitive; } public abstract Object parse(String string); } 

Trying to do this in C #, I get a compile error. Am I doing something wrong or is this feature not implemented in Sharpe?

Everyone knows that C # and Java as programming languages ​​are very similar, which is why I draw an analogy for a more detailed description of the issue. I do not ask you and do not want to compare them myself, but rather to find out which is better, so that. do not do this.

Thank you in advance!

    1 answer 1

    There is no such possibility in C #: enum is nothing more than a typed set of constants, with the ability to use it as a set of flags, for which the methods in the Enum class are defined.

    It is allowed to have values ​​of fields of an enumerated type with a value that is not defined in the type itself, for example:

     enum Foo { First, Second, Third, } // Π² ΠΌΠ΅Ρ‚ΠΎΠ΄Π΅: // Π½Π΅ Π²Ρ‹Π·Ρ‹Π²Π°Π΅Ρ‚ Π½ΠΈ ошибок компиляции, // Π½ΠΈ ошибок выполнСния Foo foo = (Foo)1234; 

    Alternatively, you can get similar behavior by describing methods in a static class:

     static class FooHelper { public static object Parse(Foo type, string value) { switch (type) { case Foo.First: // ... break; // ... default: throw new ArgumentException("type must be valid value from Foo."); } } }