How do I change the value of an attribute?

How to change variable value in base class?

  • I have a class that derives from a base class. I can access the member of the base class but the derived class treats it as it's own variable. How do I change the value of the base class variable? For example (C# Example) class A { public int value = 0; public void Display() { Console.WriteLine(value); } } class B : A { public void Update() { base.value++; } } // Main { A aClass = new A(); B bClass = new B(); bClass.Update(); a.Class.Display(); } // Result = 0. I want the result to be 1. How come I can't directly change the value of the base class?

  • Answer:

    aClass is an instance of class A. bClass is an instance of class B, which extends class A. So you have two instances of class A, one a pure instance called aClass, one the base class for bClass. When you call bClass.Update() you increment the value inside its base class, not in the separate instance belonging to aClass. Two ways you could change that behaviour are: 1. Call bClass.Display() rather than aClass.Display() 2. Declare value using "public static int value = 0;", the static keyword says value belongs to the class A itself, not to instance of class A. The second option is unlikely to be what you want.

Petze at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

You have mistaken, bClass.Display() will give you what you want

James Bond

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.