简体   繁体   中英

How do I create an auto-implemented list property in a class in C#?

To begin with I made a class with fields like this:

class Person
{
    public string name;
    public List<Thing> things = new List<Thing>();

    public Person(string name)
    {
        this.name = name;
    }
}

and directly changed the field things outside the class, but later found out that this is not the best practice as the fields of class should be private and accessed using public properties instead. I decided to change these fields into auto-implemented properties, as I currently don't require any validation within the properties:

class Person
{
    public string Name { get; set; }
    public List<Thing> Things { get; set; }

    public Person(string name)
    {
        this.Name = name;
    }
}

According the MSDN page for auto-implemented properties ( https://msdn.microsoft.com/en-us/library/bb384054.aspx ), the compiler creates a private backing field for the property.

However, with a list property I'm not sure whether the compiler automatically instantiates the list backing field , so my question is will having the lists as auto-implemented properties work as in the second example above , or do I need to instantiate the lists as well , and if so how should I do this?

I'm not sure whether the compiler automatically instantiates the list backing field

It doesn't. If you don't instantiate it, it will be null by default.

do I need to instantiate the lists as well, and if so how should I do this?

You need to instantiate it yourself. This is usually/can be done in the constructor. Eg:

public Person(string name) 
{
    this.Name = name;
    this.Things = new List<Thing>();
}

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