How to use a 'has a' relationship : Member Variable « Class « C# / CSharp Tutorial






public class Engine
{
  public int cylinders;
  public int horsepower;

  public void Start()
  {
    System.Console.WriteLine("Engine started");
  }

}

public class Car
{
  public string make;
  public Engine engine;  // Car has an Engine

  public void Start()
  {
    engine.Start();
  }

}

class MainClass
{

  public static void Main()
  {
    System.Console.WriteLine("Creating a Car object");
    Car myCar = new Car();
    myCar.make = "Toyota";

    System.Console.WriteLine("Creating an Engine object");
    myCar.engine = new Engine();
    myCar.engine.cylinders = 4;
    myCar.engine.horsepower = 180;

    System.Console.WriteLine("myCar.make = " + myCar.make);
    System.Console.WriteLine("myCar.engine.cylinders = " + myCar.engine.cylinders);
    System.Console.WriteLine("myCar.engine.horsepower = " + myCar.engine.horsepower);

    myCar.Start();
  }
}
Creating a Car object
Creating an Engine object
myCar.make = Toyota
myCar.engine.cylinders = 4
myCar.engine.horsepower = 180
Engine started








7.5.Member Variable
7.5.1.fields
7.5.2.A class with method and member variables
7.5.3.field initialization
7.5.4.Add a method to access the field variables
7.5.5.Call base constructor to init member variables
7.5.6.Use this and base together to init a class
7.5.7.How to use a 'has a' relationship
7.5.8.Illustrates how to assign default values to fields using initializers