Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access base class field from derived&&subclass

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);
                }
            }
        }
    }
like image 695
Tamazi Bagdavadze Avatar asked Apr 25 '26 10:04

Tamazi Bagdavadze


1 Answers

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.

like image 103
Selman Genç Avatar answered Apr 27 '26 22:04

Selman Genç



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!