Why can't we access enum values ​​from an enum instance in C #?

It may happen, but this question has been bothering me since yesterday. Until I found the link, then I knew that I was not very crazy lol: List as instance variables

I basically ask the opposite of the OP question. Given:

enum Coffee { BIG, SMALL } public class MyClass { private Coffee coffee; // Constructor etc. } 

Although it is Java, and the enumerations are really slightly different in both languages, I cannot make .BIG coffee or .BIG.SMALL coffee (although it makes little sense when reading, should it be possible, given that coffee is of type Coffee) in C #?

+6
source share
2 answers

This does not apply to transfers. This applies to access to static members in general.

Java has a design flaw (IMO) that allows you to refer to static members as members of an instance through an expression of this type. This can lead to very confusing code:

 Thread thread = new Thread(...); thread.start(); // This looks like it makes the new thread sleep, but it actually makes the // current thread sleep thread.sleep(1000); 

In addition, there is no validation because the value of the expression does not matter:

 Thread thread = null; thread.sleep(1000); // No exception 

Now consider that the enumeration values ​​are implicitly static, and you can understand why there is a difference.

The fact that you admitted that "this makes little sense when reading" suggests that at heart you agree that it is a flaw in Java, not inside C # :)

+10
source

In C # (unlike Java), it is illegal to access a static field through an instance of this class.

If you write this:

 coffee.BIG.SMALL 

Then you get the error:

The user "coffee.SMALL" cannot be accessed with reference to the instance; qualify it instead of type name

This code will also not work for the same reason:

 void Foo(coffee c) { // Member 'coffee.SMALL' cannot be accessed with an instance reference Console.WriteLine(c.SMALL); } 
+4
source

Source: https://habr.com/ru/post/922665/


All Articles