Aks
Aks

Reputation: 5236

C# Inheritance : modify base class variable from derived class

I have a base class that looks as follows

public class base 
{
      public int x;
      public void adjust()
      {
           t = x*5;
      }
}

and a class deriving from it. Can I set x's value in the derived class's constructor and expect the adjust() function to use that value?

Upvotes: 5

Views: 22530

Answers (2)

Giuseppe Accaputo
Giuseppe Accaputo

Reputation: 2642

Yes, it should work.

The following, slightly modified code will print 'Please, tell me the answer to life, the universe and everything!' 'Yeah, why not. Here you go: 42'

public class Derived : Base
{
    public Derived()
    {
        x = 7;
    }
}

public class Base
{
    public int x;
    public int t;
    public void adjust()
    {
        t = x * 6;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Base a = new Derived();
        a.adjust();

        Console.WriteLine(string.Format("'Please, tell me the answer to life, the universe and everything!' 'Yeah, why not. Here you go: {0}", a.t));
    }
}

Upvotes: 3

Fredrik Mörk
Fredrik Mörk

Reputation: 158289

Yes, that should work entirely as expected, even though your code sample does not quite make sense (what is t?). Let me provide a different example

class Base
{
    public int x = 3;
    public int GetValue() { return x * 5; }
}
class Derived : Base
{
    public Derived()
    {
        x = 4;
    }
}

If we use Base:

var b = new Base();
Console.WriteLine(b.GetValue()); // prints 15

...and if we use Derived:

var d = new Derived();
Console.WriteLine(d.GetValue()); // prints 20

One thing to note though is that if x is used in the Base constructor, setting it in the Derived constructor will have no effect:

class Base
{
    public int x = 3;
    private int xAndFour;
    public Base()
    {
        xAndFour = x + 4;
    }
    public int GetValue() { return xAndFour; }
}
class Derived : Base
{
    public Derived()
    {
        x = 4;
    }
}

In the above code sample, GetValue will return 7 for both Base and Derived.

Upvotes: 10

Related Questions