How to do constructor chaining in C#

前端 未结 8 1538
挽巷
挽巷 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:57

    You use standard syntax (using this like a method) to pick the overload, inside the class:

    class Foo 
    {
        private int id;
        private string name;
    
        public Foo() : this(0, "") 
        {
        }
    
        public Foo(int id, string name) 
        {
            this.id = id;
            this.name = name;
        }
    
        public Foo(int id) : this(id, "") 
        {
        }
    
        public Foo(string name) : this(0, name) 
        {
        }
    }
    

    then:

    Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");
    

    Note also:

    • you can chain to constructors on the base-type using base(...)
    • you can put extra code into each constructor
    • the default (if you don't specify anything) is base()

    For "why?":

    • code reduction (always a good thing)
    • necessary to call a non-default base-constructor, for example:

      SomeBaseType(int id) : base(id) {...}
      

    Note that you can also use object initializers in a similar way, though (without needing to write anything):

    SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
             z = new SomeType { DoB = DateTime.Today };
    

提交回复
热议问题