E
E
ellz2019-02-05 15:51:04
.NET
ellz, 2019-02-05 15:51:04

Why does System.NullReferenceException: 'Object reference not set to an instance of an object occur?

Hello. There is this method:

[HttpPost]
        [Route("postTourInfo")]
        public string Post([FromBody] GettingTourInfo value)
        {
            Tours tours = new Tours();
         
            tours.tourInfos[0].beachType = "one";// здесь возникает ошибка
            tours.tourInfos[1].beachType = "two";

            return JsonConvert.SerializeObject(tours);
        }

and these classes:
public class GettingTourInfo
    {
        public string fromCity { get; set; }
        public string toCountry { get; set; }
        public DateTime departureDate { get; set; }
        public int amountNights { get; set; }
        public int amountAdults { get; set; }
    }

    public class TourInfo
    {
        public int statusCode { get; set; } //200, если туры найдены, 404 - если не найдены
        public string tourName { get; set; } //названиеТура
        public string hotelName { get; set; } //названиеОтеля
        public int hotelRating { get; set; } //рейтингОтеля
        public int line { get; set; } //линия
        public string beachType { get; set; } //типа поляжа(песок, песок с галькой, галька, платформа)
        public int distanceToBeach { get; set; }// растояние до пляжа
        public int distanceToAirport { get; set; } // растояние до аэропорта
    }

    public class Tours
    {
        public List<TourInfo> tourInfos { get; set; }
    }

I send a request through Postman and catch in response
System.NullReferenceException: 'Object reference not set to an instance of an object

In the body of the method, I decided to simply check whether filling the object will work, etc.
What could be the problem? The idea is to return a string with two JSON arrays, where everything except beachType will be null.
.Net Core 2.0 project.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2019-02-05
@ellz

Because tours.tourInfosno one has made a list. You only declared it, but did not become new .

B
Binky, 2019-02-05
@Binky

public class Tours
{
public List tourInfos { get; set; } = new List();
}
or create a parameterless constructor where the list will be initialized. Otherwise, it is really null and the compiler did not deceive you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question