How to do constructor chaining in C#

前端 未结 8 1626
挽巷
挽巷 2020-11-22 16:25

I know that this is supposedly a super simple question, but I\'ve been struggling with the concept for some time now.

My question is, how do you chain constructors

8条回答
  •  感情败类
    2020-11-22 16:38

    This is best illustrated with an example. Imaging we have a class Person

    public Person(string name) : this(name, string.Empty)
    {
    }
    
    public Person(string name, string address) : this(name, address, string.Empty)
    {
    }
    
    public Person(string name, string address, string postcode)
    {
        this.Name = name;
        this.Address = address;
        this.Postcode = postcode;
    }
    

    So here we have a constructor which sets some properties, and uses constructor chaining to allow you to create the object with just a name, or just a name and address. If you create an instance with just a name this will send a default value, string.Empty through to the name and address, which then sends a default value for Postcode through to the final constructor.

    In doing so you're reducing the amount of code you've written. Only one constructor actually has code in it, you're not repeating yourself, so, for example, if you change Name from a property to an internal field you need only change one constructor - if you'd set that property in all three constructors that would be three places to change it.

提交回复
热议问题