+ 3

How to use Inheritance and constructor to pass variables correctly?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace My_program { class Program { static void Main(string[] args) { House h = new House(1, 300, 5); h.About(); } } class Building { #region Variables //Buildings can be placed at diferent loacations protected int Location { get; set; } //Cost to build it protected int Cost { get; set; } #endregion protected Building(int Location, int Cost) { this.Location = Location; this.Cost = Cost; //This line is executed not as intended. Why Cost becomes 1? Console.WriteLine("Building in squere {0}, costing {0}, has been built!", Location, Cost); } public void About() { //Here everything is fine Console.Write("Building is placed in squere {0}, and cost {1} ", Location, Cost); } } class House : Building { //Inhabitants of the building private int People; //Building a house public House(int Location, int Cost, int People) : base(Location, Cost) { this.People = People; Console.WriteLine("House has {0} people living here", People); } } }

4th Nov 2017, 11:05 PM
Jacob “uhgfel” L
Jacob “uhgfel” L - avatar
5 ответов
+ 3
I'm trying to pass int Cost to to Building class and immediately after that Output it's variables to console. However for some reason Cost (which in main Class is written as 300) Is outputted as 1 in Building class constructor. This is my problem. Afterwards I tried using Building method separately and it worked just fine. If you would be able to explain why, I would appreciate.
4th Nov 2017, 11:19 PM
Jacob “uhgfel” L
Jacob “uhgfel” L - avatar
+ 3
ok so if I create another building, lets say a shop or a tower... I whould have to declare all other instance variables in the same place ? (shop variables would be in the same place as house variables) Then what's the point of having derived classes? Clearly I don't understand what you are trying to say. Could you correct a code as you think it should be. That may help more.
4th Nov 2017, 11:54 PM
Jacob “uhgfel” L
Jacob “uhgfel” L - avatar