We help IT Professionals succeed at work.

In C#, how to access base class variable from child class?

Peter Pang
Peter Pang asked
on
3,280 Views
Last Modified: 2018-06-04
In C#, how to access base class variable from child class?

e.g.
Base Class
   class TestBase
    {
        protected int a;

        public TestBase(int i)
        {
            a = i;
        }

        protected TestBase()
        {

        }

        public void Update(int i)
        {
            a = i;

            TestChild child = new TestChild();
            child.Update("Hello World ");
        }

    }

ChildClass
   class TestChild:TestBase
    {
        private string msg;
        public void Update (string s)
        {
            msg = s+ a.ToString();
            Console.WriteLine(msg);

        }
    }

Calling
       private void btnTest_Click(object sender, EventArgs e)
        {
            TestBase t = new TestBase(1);
            t.Update(100);

        }

Result
Hello World 0

Problem
I was hoping to get Hello World 100.
How to get child class to access base class variable, in this case int a ?
Comment
Watch Question

Freelance programmer / Consultant
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Francis EmpleoSystem Developer

Commented:
Actually you can't. The reason is obvious because it is a protected property. You can access this by creating a public method inside you base class and call it from your child class
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
There is no need to create a public method in the base/parent class.  The child *can* update a protected variable since the child inherited the parent (or derived from the parent).
protected: Access is limited to the containing class or types derived from the containing class.


- Source
Another proof of concept.
using System;

namespace EE_Q29097909
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = new TestBase(1);
            t.Update(100);
            Console.ReadLine();
        }
    }

    class TestBase
    {
        protected int a;

        public TestBase(int i)
        {
            a = i;
        }

        protected TestBase() {; }

        public void Update(int i)
        {
            a = i;

            var child = new TestChild();
            Console.WriteLine($"Base class a = {a}; Child a = {child.a}");
            child.a = a;
            Console.WriteLine($"Base class a = {a}; Child a = {child.a}");
            child.Update("Hello World");
        }
    }

    class TestChild : TestBase
    {
        public void Update(string s)
        {
            Console.WriteLine($"{s} {a}");
        }
    }
}

Open in new window

Which produces the following output -Capture.PNGIt is as Kyle stated, the OP instantiates a new Child class but does not give the child class instance the updated value for a.  Assigning the child's 'a' from the base update method is one possible solution.

-saige-
Francis EmpleoSystem Developer

Commented:
Oh yeah youre right. Sorry forgot about the inheritance. Thanka for correcting :)
Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT

Commented:
Also just a note that with reflection the protection model goes away.  I've been able to update private variables in a 3rd party DLL when needed.  Not saying that you *should* do it, and if you do do it you need to understand all the impacts of said change, but you *CAN* do it.
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
re inheritance - see the code in the very first comment.
AndyAinscowFreelance programmer / Consultant
CERTIFIED EXPERT

Commented:
The code in the question didn't use a parent-child relationship.  Hence it didn't work.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.