views:

158

answers:

3

Hello :)

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 :)

+6  A: 

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; }
        }
   }
Henk Holterman
Thanks a lot, I had simply forgotten. :) Sorry for asking so basic questions, it's been long since I last coded in C#.
Lazlo
@Lazlo - You shouldn't apologize, that is what this site is for.
David Basarab
+2  A: 

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.

David Basarab
+3  A: 

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

jeroenh