简体   繁体   中英

How to implement a List<T> property in a C# class?

I have the code below:

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public List<Blog> Blogs { get; set; }
}

and the Blog class itself:

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime PublicationDate { get; set; }
}

I instantiate the list property in Program class (main method) by this way:

lBlog.Add(new Blog { Id = 1, Title = "War & Peace", PublicationDate = new DateTime(2020, 02, 23) }); 

So far - good. But, when I'm trying to add it to author object it's empty

author.Blogs.AddRange(lBlog);   

You should initialize Blogs list in Author class constructor

public class Author
{
    public Author()
    {
        Blogs = new List<Blog>();
    } 

    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public List<Blog> Blogs { get; set; }
}

Or use property initializer for that (it's available from C# 6). In this case make sense to make a property readonly (to prevent overwriting a property from outside)

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public List<Blog> Blogs { get; } = new List<Blog>();
}

Try this:

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public List<Blog> Blogs { get; set; } = new List<Blog>();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM