Question

Here is my current layout: (the question is the comment)

class A
{  
    int foo;  
}

class B : A {}

class C : B
{
    void bar()
    {
        //I want to access foo
        base.foo; // Doesn't work
        base.base.foo // Doesn't work, of course
    }
}

As you can see, I cannot access members of A by using base in C. How could I access it? Thanks :)

Was it helpful?

Solution

If you make foo protected,

class A
{  
    protected int foo;  
}

then a simple base will do:

  void bar()
  {
        //I want to access foo
        base.foo; // will work now
        // base.base.foo // Doesn't work, of course
  }

But it would be better to build a (protected) property around foo:

   class A
   {  
        private int _foo;  
        protected int Foo 
        {
           get { return _foo; }
           set { _foo = value; }
        }
   }

OTHER TIPS

The field in A is declared private. It should be protected for derived classes to access it.

Put public in front of int foo;

class A
{  
    public int foo;  
}

class B : A {}

class C : B
{
    void bar()
    {
        //I want to access foo
        base.foo; // Now you can see it
    }
}

By default unless you specify otherwise all members are private.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top