How do I add a list to an object?

So basically what I’m trying to do is making a parking ticket system. I’ve got two classes one that contains info for a Car and one for a Ticket. I want the system to show all the tickets a car registration has gotten.

public class Car
    {

        public string registrationNumber { get; set; }


        public string carBrand { get; set; }


        public string carColor { get; set; }

        public List<Ticket> ticketlist {get; set;}
        
        public void AddParkingTicket(Ticket newTicket)
        {
            ticketList.Add(newTicket);
        }
    }
}

 public class Ticket
    {
        public Ticket(int TicketID, DateTime date, string comment, int parkeringareaID, int parkingOfficerID)
        {
        }

      
        public int TicketID { get; set; } = 0;

        
        public DateTime date { get; set; }

       
        public string commenter { get; set; }


       
        public int parkingsAreaID { get; set; }

       
        public int parkingsOfficerID { get; set; }

    }
}
  

List<Car> list = new List<Car>();
    public TicketController()
    {
        

        Ticket ticket1 = new Ticket(1, DateTime.Now, "handicap parking", 1, 2);
        Car car1 = new Car { registrationNumber = "BT66358", carBrand = "BMW", carColor = "Gul" };
        
        car1.AddParkingTicket(ticket1)

        list.Add(car1);
    }

my current output is this

[
    {
        "registrationNumber": "BT66358",
        "carBrand": "BMW",
        "carColor: "Yellow",
        "ticketlist": null
    }
]

I’m not sure what I’m doing wrong, I’ve tried to change the class contructors aswell, but no success. I want the output to also show the info of the ticket for that given registration number

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

change ticketList to ticketlist

 public void AddParkingTicket(Ticket newTicket)
        {
            ticketlist.Add(newTicket);
        }

you also need to add constructor to Car to initialize collection, otherwise you get error

public Car()
        {
            this.ticketlist = new List<Ticket>();
        }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x