简体   繁体   中英

How do I instantiate a property in a class where the property type is also a class?

I have a class

public classs User
{
  public string Id {get; set;}
  public Details userdetails { get; set;}
}

public classs Details 
{
  public string Name {get; set;}
  public string Address { get; set;}
}

Now if i do the following

  User usr = new User();
  usr.userdetails.Name ="TestName";

It gives an error saying "userdetails" is null. I thought it would have instantiated the sub class and in the quick watch I would be able to drill down and see te properties?

You can instantiate it inside the User constructor :

public class User
{
    public string Id {get; set;}
    public Details userdetails { get; set;}

    public User() {
        this.userdetails = new Details();
    }
}

Constructor MSDN documentation for your reference

EDIT:

Also as pointed out in the comments, there's a shorthand syntax for the above, which is this:

public class User
{
    public string Id {get; set;}
    public Details userdetails { get; set; } = new Details();
}

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