base() and this() constructors best practices

后端 未结 5 1732
予麋鹿
予麋鹿 2020-12-02 05:47

Under what conditions am I supposed to make the :base() and :this() constructor calls following my constructor\'s parentheses (or even in other pl

5条回答
  •  情话喂你
    2020-12-02 06:39

    First off, when they're mandatory.

    When a class Derived is derived from a class Base, and Base does not have a default (parameterless) constructor, Derived must call base() explicitly with parameters.

    public class Base {
        public Base(int i) { }
    }
    
    
    public class Derived : Base {
        // public Derived() { } wouldn't work - what should be given for i?
        public Derived() : base(7) { }
        public Derived(int i) : base(i) { }
    }
    

    When is it good practice? Whenever you want to call a different constructor.

    Suppose you add, in my previous example, content to the constructors in Derived.

    public class Derived : Base {
        // public Derived() { } wouldn't work - what should be given for i?
        public Derived() : base(7) {
            Console.WriteLine("The value is " + 7);
        }
        public Derived(int i) : base(i) {
            Console.WriteLine("The value is " + i);
        }
    }
    

    You notice the duplication here? It's simpler to call the this() constructor.

    public class Derived : Base {
        // public Derived() { } wouldn't work - what should be given for i?
        public Derived() : this(7) { }
        public Derived(int i) : base(i) {
            Console.WriteLine("The value is " + i);
        }
    }
    

提交回复
热议问题