wootscootinboogie
wootscootinboogie

Reputation: 8705

Initialize an array of a class in a constructor

I have a class Garage that has a property which is an array of type Car, which is another class in the program. I've tried several iterations and get run-time errors on most of them. I get a NullRefernceException whenever I try to run it. This happens in the Program class where I try to access the length property of the CarLot array.

I know this has something to do with the CarLot property of the Garage class being an array instead of just Car. What piece am I missing here so that the array isn't set to null when the program tries to use it?

class Program
{
    static void Main(string[] args)
    {
        Garage g = new Garage();
        //this is where the exception occurs
        g.CarLot[0] = new Car(5, "car model");
        Console.ReadLine();
    }
}

public class Garage 
{
    public Car[] CarLot { get; set; }
    public Garage() { }
    //this should be able to be 0 or greater
    public Garage(params Car[] c)
    {
        Car[] cars = { };
        CarLot = cars;
    }
}

public class Car
{
    public int VIN { get; set; }
    public int Year { get; set; }
    public string Model { get; set; }
    public Car(int _vin, string _model)
    {
        _vin = VIN;
        _model = Model;
    }
    public Car() { }
    public void Print()
    {
        Console.WriteLine("Here is some information about the car {0} and {1} ");
    }
}

Upvotes: 2

Views: 19592

Answers (2)

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15158

I know it's not the exact thing you're asking for, but how about something like this ? Wouldn't it be much easier ?

    static void Main(string[] args)
    {
        var garage = new List<Car>();
        //this is where the exception occurs
        garage.Add(new Car(5, "car model"));
    }

    public class Car
    {
        public int VIN { get; set; }
        public int Year { get; set; }
        public string Model { get; set; }
        public Car(int _vin, string _model)
        {
            _vin = VIN;
            _model = Model;
        }
        public Car() { }
        public void Print()
        {
            Console.WriteLine("Here is some information about the car {0} and {1} ");
        }

    }

Upvotes: 1

Timothy Randall
Timothy Randall

Reputation: 18654

Instead of using an auto property for your array, you can use a private variable to initialize your array when your parameterless constructor is called in Main.

e.g.

private Car[] carLot = new Car[size];
public Car[] CarLot
{
     get { return carLot; }
     set { carLot = value; }
}

Alternatively, in your parameterless constructor for Garage you can go ahead and initialize the array at that point.

Either way, your array has to be instantiated before you can assign values to it. http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

Upvotes: 3

Related Questions