Search code examples
listconstructorinitializing

Object reference not set to an instance of an object (noob)


I have this simple code, but I get the error "Object reference not set to an instance of an object" when I try to access the "MyCarslist" initialized in my constructor. What am I missing?

 class Cars
{
    public List<Car> MyCarslist { get; set; }


    public void AddCar(Car car)
    {
      MyCarslist.Add(car);
      Console.WriteLine(MyCarslist.Count);
    }

    public Cars()
    {
    List<Car> MyCarslist = new List<Car>();
    }

Both Mycarslist.add(car); and Console.WriteLine(MyCarslist.Count); give the error


Solution

  • You are declaring a variable with this line

    List MyCarslist = new List();

    not setting the property. Try this..

    MyCarslist = new List();

    Thanks, O