3

I can't understand why I have access to Base class's field. I have no object of Base class, and private fields are not inherited as I know. When I try to get field "i" of class "SubDerived" with reflection, it cannot find it. please anyone explain..

using System;

    namespace tests
    {
        public class Test
        {
            static void Main()
            {
                Base.SubDerived a = new Base.SubDerived();
                a.f();

                Console.ReadLine();
            }
        }

        class Base
        {
            int i = 1;

            public class SubDerived : Base
            {
                public void f()
                {
                    Console.WriteLine(base.i);
                }
            }
        }
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397

1 Answers1

6

SubDerived is nested,that's why it has access to private members of the parent type.If you make it like this:

class Base
{
   int i = 1;
}
public class SubDerived : Base
{
   public void f()
   {
        Console.WriteLine(base.i);
   }
}

You won't be able to access i.You need to make it protected.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184