0

I have this Car class,

public class Car
{
    public string Name { get; set; }
    public string Color { get; set; }

    public Car(): this ("", "") { }

    public Car(string name, string color)
    {
        this.Name = name;
        this.Color = color;
    }
}

Also I have Garage class containing a collection of Cars.

public class Garage
    {
        public List<Car> CarList { get; set; }

        public Garage() { }

        public Garage(int carCount)
        {
            this.CarList = new List<Car>(carCount);
        }

        public Garage(params Car[] cars)
        {
            this.CarList = new List<Car>();
            foreach (Car car in cars)
               this.CarList.Add(car);
        }
    }

I tried to initialize an instance of a Garage in Main(),

Car car1 = new Car("BMW", "black");
Car car2 = new Car("Audi", "white");
Garage garage = new Garage(car1, car2);

I get an error, "A field initializer cannot reference the non-static field, method, or property". What I'm doing wrong?

Sam
  • 7,252
  • 16
  • 46
  • 65
astrid
  • 9
  • 2

1 Answers1

1

"Instance fields cannot be used to initialize other instance fields outside a method." Please check this page ERROR page from MS.

So either make car object static as;

    static Car car1 = new Car("BMW", "black");
    static Car car2 = new Car("Audi", "white");

    Garage garage = new Garage(car1, car2);

Or declare it

     Car car1 = new Car("BMW", "black");
     Car car2 = new Car("Audi", "white");
     Garage garagel;

and then use inside any other method

    garage = new Garage(car1, car2);
H. Mahida
  • 2,356
  • 1
  • 12
  • 23