0

I'm trying to get a value from an Interface. I have a function like this:

public IEnumerable<Car> CreateCars()
{
    IEnumerable<Car> carList = new List<Car>()
    {
        new Car{ Id = 1, Name = "Opel", CarProperties = { Color= "White", Model= "2012" }},
        new Car{ Id = 2, Name = "Citroen", CarProperties = { Color= "Blue", Model = "2014" }},
        new Car{ Id = 6, Name = "Peugeot", CarProperties = { Color= "Red", Model = "2013" } }
    };

    return carList;
}

When I call the method it gives exception:

object reference not set to instance of an object.

I searched but could not find an answer. Can you help me to solve this problem?

gunr2171
  • 10,315
  • 25
  • 52
  • 75
koirene
  • 13
  • 1
  • 4

2 Answers2

4
new Car{ Id = 1, Name = "Opel", CarProperties = { Color= "White", Model= "2012" }}

This line is equivalent to this:

car = new Car();
car.Id = ...
car.Name = ...
car.CarProperties.Color = ...

The fact that you're getting a NullReferenceException leads me to believe car.CarProperties is null.

One possible fix is to change the Car constructor to initialize the CarProperties property or its backing field.

public class Car
{
    public SomeType CarProperties {get; private set;}

    public Car()
    {
        CarProperties = new SomeType();
    }    
}
dcastro
  • 59,520
  • 20
  • 126
  • 147
2

I guess the exception is raised here:

new Car{ Id = 1, Name = "Opel", CarProperties = { Color= "White", Model= "2012" }},

You should initialize CarProperties with its corresponding type. Something like:

new Car { Id = 1, Name = "Opel", CarProperties = new CarProperty { Color= "White", Model= "2012" } },

You can also initialize the CarProperties property in the constructor of the Car class.

Henk Mollema
  • 36,611
  • 11
  • 79
  • 100
  • 1
    I think *You should initialize `CarProperties` with its corresponding type* doesn't make much sense. How about *You should initialize `CarProperties` by creating a new instance of `CarProperty`*, which is what your code actually does? – sloth May 30 '14 at 14:15