Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the recommended way to initialize child object collection inside a class. I tried this but this does not work.

SQL
public class Student
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime EnrollmentDate { get; set; }

        public IList<Enrollment> Enrollments { get; set; }

        public bool IsNew
        {
            get
            {
                return this.ID == default (int);
            }
        }

        public Student
        {
            this.Enrollments= new IList<Enrollment>();
        }
    }
Posted

IList<T> is just a collection interface. You cannot create instance of interface. You must use concrete type which implements IList<T> interface.
This will do the job:
this.Enrollments = new List<Enrollment>();


More information you'll find here:
http://msdn.microsoft.com/pl-pl/library/System.Collections.Generic%28v=vs.110%29.aspx[^]
http://msdn.microsoft.com/pl-pl/library/5y536ey6%28v=vs.110%29.aspx[^]
 
Share this answer
 
v3
IList is a Interface. you cannot create an object for Interface. use new List<>() instead of new IList<>()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900