Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic field const vs. any old reference field const behavior

Tags:

c#

This probably has a simple explanation I'm failing to see, but why is the following code 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()': not all code paths return a value?

Why does the fact that nullObject being dynamic makes the compiler not be able to assert that nullObject will always be null?

EDIT: Expanding on the question, and based on smoore's answer, why does the compiler allow dynamic const fields to begin with? Isn't it kind of self defeating? I know this scenario has no real application at all and it's frankly quite pointless but I stumbled upon it by sheer accident and just got curious.

like image 877
InBetween Avatar asked May 09 '13 15:05

InBetween


1 Answers

Because dynamic objects are not resolved at compile time, so the compiler has no idea that it will always be null. The dynamic object won't be resolved until run time.

EDIT:

I see your confusion, why even allow a const dynamic?

My guess is that the Dynamic could be changed to a non-nullable type, in which case ToString would not return a value, but that's just a guess. I'm also thinking that you might still want to have the ability to have a constant dynamic, so that you can ensure the value won't change outside of the static constructor, but not know the type until run-time.

Another possibility, as Servy point out, is that it's such a corner-case that it's not worth fixing.

like image 56
Seth Moore Avatar answered Oct 08 '22 17:10

Seth Moore