greenonion
greenonion

Reputation: 105

Accessing Instance Variable Hidden By Static Variable Without Base Keyword

How come I can't access the hidden instance variable a in the line (int gimmeValue = shinyNewBObject.a;) ? I understand that I can use the base keyword to access the instance a. However, I thought that the compiler would use the object reference in shinyNewBObject to rule out static variables. If the static version of a is ruled out, the instance version of a would become unhidden and therefore accessible.

What's going on here? Did the compiler create a list of all a identities in the assembly and ruled out the instance variable because it's hidden before it ruled out the other a because it's static?

class A
{
    public int a;
}

class B : A
{
    new public static int a;

    public void m()
    {
        B shinyNewBObject = new B();
        int gimmeValue = shinyNewBObject.a; //Error
        gimmeValue = base.a;
    }
}

Upvotes: 2

Views: 278

Answers (2)

greenonion
greenonion

Reputation: 105

I think I found the answer:

I needed to look at the member look-up section of the specification (7.4).

"the effect of the look-up rules is simply that derived members hide base members with the same name or signature. Such single-inheritance look-ups are never ambiguous."

I think what happens when aobj.a is considered by the compiler is aobj is ignored for the time being and just a is considered.

The compiler goes to the A class definition which has all of the static and instance members implicitly or explicitly and sees the two a members. Both are accessible based on (3.5) so they go in the set of possibilities. Then the hidden variable is removed leaving the static one.

Finally 'aobj' is considered and an error occurs because an instance reference can't access the static variable.

There might be some problems with my story. If so, please correct me because I made some guesses.

Upvotes: 1

Kirk Woll
Kirk Woll

Reputation: 77606

I'm not entirely sure what part of the C# spec dictates why it won't let you access the base type variable when it's obscured by a static field in the subclass, but to workaround it, you can just cast to A:

int gimmeValue = ((A)shinyNewBObject).a; 

Upvotes: 4

Related Questions