0

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

humudu
  • 699
  • 1
  • 7
  • 13

2 Answers2

0

You are declaring a variable with this line

List MyCarslist = new List();

not setting the property. Try this..

MyCarslist = new List();

Thanks, O

0

Change this:

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

to this:

public Cars()
{
    this.MyCarslist = new List<Car>();
}
lante
  • 7,192
  • 4
  • 37
  • 57