AutoMapper and System.NullReferenceException: Object reference not set to an instance of an object.

Advice on dealing with strange errors (in general):

What’s the difference between the following lines of code (1 vs 3&4)?

Code Snippet
  1. dtoList.Add(AutoMapper.Mapper.Map<Model.example, Dto.example>(example));
  2. var dtoExample = AutoMapper.Mapper.Map<Model.example, Dto.example>(example);
  3. dtoList.Add(dtoExample);

Answer: Potentially many hours of hair pulling and frustration. By combining the two lines of code into one (line 1) it appears as though the error “System.NullReferenceException: Object reference not set to an instance of an object.” is coming from AutoMapper. By separating the the code into two lines it is not only readable, but easier to debug. The error will NOT occur on line 3 thereby ruling out AutoMapper and will occur on line 4, because the dtoLists object was not instantiated and therefore is null. You cannot add something to a null object.

Posted in Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *