You generally don't want to nest class definitions the way you did. What if you had a car that could use a different kind of engine? Like, say, a 4-liter vs. a 2-liter? Or normally aspirated vs. turbo charged? What you might want to do instead is pass in the Engine
as a parameter to the Car
.
Regarding your actual problem of obtaining values from these objects, you also need to define how values can be obtained and/or changed. A constructor does the initial work, but what if the Engine
or Car
have values that need to be changed or obtained during the program's lifestyle? You need accessors.
public class Car
{
public string name { get; private set; }
public string model { get; private set; }
public Engine engine { get; private set; }
public Car(string name, string model, Engine engine)
{
this.name = name;
this.model = model;
this.engine = engine;
}
}
class Engine
{
public string number { get; private set; }
// other values as necessary
public Engine(string number)
{
this.number = number;
}
}
var newCar = new Car('Volvo', 'Hatchback', new Engine('someNumber'));
var engineNumber = newCar.engine.number;
In this example, you can obtain the data you want by referencing an object property (get
), but you won't be able to change that data in the same way (private set
). Instead, you'd need to make object methods (read: functions, if you're new to OOP) to explicitly change those values.