Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Inheritance : modify base class variable from derived class

Tags:

c#

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?

like image 568
Aks Avatar asked Mar 28 '11 07:03

Aks


2 Answers

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.

like image 105
Fredrik Mörk Avatar answered Sep 27 '22 19:09

Fredrik Mörk


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));
    }
}
like image 21
Giuseppe Accaputo Avatar answered Sep 27 '22 19:09

Giuseppe Accaputo