C # Inheritance: changing a base class variable from a derived class

I have a base class that looks like this

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

and the class arising from it. Can I set the value of x in the constructor of the derived class and expect the adjust() function to use this value?

+4
source share
2 answers

Yes, this should work fully as expected, even if your sample code is not entirely clear (what is t ?). Let me give you another 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 

It should be noted that if x 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 example, GetValue will return 7 for Base and Derived .

+9
source

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' '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}", at)); } } 
+2
source

Source: https://habr.com/ru/post/1345510/


All Articles