Dynamic field Const against any old behavior of a constant field reference

This probably has a simple explanation that I don't see, but why the following law is legal:

public struct Foo { const object nullObject = null; public override string ToString() { if (nullObject == null) { return base.ToString(); } } } 

While the following,

  public struct Foo { const dynamic nullObject = null; public override string ToString() { if (nullObject == null) { return base.ToString(); } } } 

gives the following compile-time error: Foo.ToString () ': do not all code paths return a value ?

Why does the fact that nullObject is dynamic prevent the compiler from asserting that nullObject will always be null ?

EDIT . Turning around the question and based on smoore's answer, why does the compiler allow dynamic const fields? Start with? Isn't that self-destruction? I know that this scenario has no real application, and it is frankly completely pointless, but I stumbled upon it just by accident and just became curious.

+6
source share
1 answer

Because dynamic objects are not resolved at compile time, so the compiler has no idea that it will always be null. A dynamic object will not be resolved until runtime.

EDIT:

I see your confusion, why even enable const dynamics?

My assumption is that Dynamic can be changed to a non-nullable type, in which case ToString will not return a value, but this is just an assumption. I also think that you can still be able to have constant dynamics so that you can ensure that the value does not change outside the static constructor, but does not know the type until runtime.

Another possibility, as Servy points out, is that it is such a corner case that it is not worth fixing.

+6
source

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


All Articles