Mark
Mark

Reputation: 7818

Trouble populating a model with a dictionary item

I have a couple of classes I'm having difficulty populating:

   public class ta_Room
   {
    public string url { get; set; }
    public double price { get; set; }
    public string room_code { get; set; }
   }

   public class ta_Hotel2
   {
    public int hotel_id { get; set; }
    public Dictionary<string, ta_Room> room_types { get; set; }
   }

In my controller I have:

    [HttpGet]
    public ta_Hotel2 hotel_inventory() //int api_version, string lang)
    {
        {
            ta_Room room = new ta_Room();
            room.price = 23;
            room.room_code = "1";
            room.url = "http://www.nme.com";

            ta_Hotel2 hotel = new ta_Hotel2();
            hotel.room_types.Add("Single", room);

However I get a NullReferenceException on the last line above.

In the screenshot below, it shows both the hotel and room object have been created - can anyone please advise what I've done wrong please?

Thank you,

Mark

ss

Upvotes: 0

Views: 43

Answers (2)

Hope
Hope

Reputation: 1302

You cannot assign a value to hotel.room_types before you initialize. Like the way Efran suggest, use a public constructor in ta_Hotel2 class will solve your issue.

Upvotes: 1

Efran Cobisi
Efran Cobisi

Reputation: 6484

The error is due to the fact you are not building the instance of room_types inside ta_Hotel2. You should add a constructor as follows or just instantiate it within hotel_inventory():

public class ta_Hotel2
{
    public int hotel_id { get; set; }
    public Dictionary<string, ta_Room> room_types { get; set; }

    public ta_Hotel2()
    {
       room_types = new Dictionary<string, ta_Room>();
    }
}

Also note that, from an encapsulation point of view, I would also make the setter of room_types private after that. And, as a side note, I would also rename your classes and members as suggested here.

Upvotes: 3

Related Questions