Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base() and this() constructors best practices

Under what conditions am I supposed to make the :base() and :this() constructor calls following my constructor's parentheses (or even in other places in the code). When are these calls good practices and when are they mandatory?

like image 701
explorer Avatar asked Sep 26 '10 11:09

explorer


People also ask

What is this () in constructor in C#?

The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name. Another usage of “this” keyword is to call another constructor from a constructor in the same class.

Which is the correct way to call the base class constructor?

For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.

Can we call one constructor from another constructor in C#?

To call one constructor from another within the same class (for the same object instance), C# uses a colon followed by the this keyword, followed by the parameter list on the callee constructor's declaration. In this case, the constructor that takes all three parameters calls the constructor that takes two parameters.


3 Answers

: base(...)

If you omit the call to a base constructor it will call the default base constructor automatically.

It is mandatory to call a base constructor explicitly if there is no default constructor.

Even if there is a default constructor you may still wish to call a different constructor than the default constructor. In this case you may still wish to use base(foo, bar) to call a different constructor than the base constructor.

I do not consider it to be a bad practice to omit base() when you want to call to the base class default constructor, although if you like to be explicit I see no harm in including it. It is a matter of taste.

: this(...)

This syntax allows you to call one constructor with a different signature from another within the same class. It is never mandatory to do this, but can sometimes be useful.

An example of when it can be useful is for reusing common code in the constructors. For example in C# 3.5 or before you may want to simulate optional parameters on a constructor:

Foo(int x, int y)
{
     this.x = x;
     this.y = y;
}

Foo(int x) : this(x, 10) {}  // y defaults to 10

With C# 4.0 optional parameters are now available which reduces the need for this approach.

An alternative way to reuse code in constructors is to factor it out into a static function which is called from each constructor that wishes to use it.

like image 143
Mark Byers Avatar answered Oct 17 '22 20:10

Mark Byers


Use base when there is inheritance, and a parent class already provides the functionality that you're trying to achieve.

Use this when you want to reference the current entity (or self), use it in the constructor's header/signature when you don't want to duplicate functionality that is already defined in another constructor.

Basically, using base and this in a constructor's header is to keep your code DRY, making it more maintainable and less verbose

Here's an absolutely meaningless example, but I think it illustrates the idea of showing how the two can be used.

class Person
{
    public Person(string name)
    {
        Debug.WriteLine("My name is " + name);
    }
}

class Employee : Person
{
    public Employee(string name, string job)
        : base(name)
    {
        Debug.WriteLine("I " + job + " for money.");
    }

    public Employee() : this("Jeff", "write code")
    {
        Debug.WriteLine("I like cake.");
    }
}

Usage:

var foo = new Person("ANaimi");
// output:
//  My name is ANaimi

var bar = new Employee("ANaimi", "cook food");
// output:
//  My name is ANaimi
//  I cook food for money.

var baz = new Employee();
// output:
//  My name is Jeff
//  I write code for money.
//  I like cake.
like image 33
ANaimi Avatar answered Oct 17 '22 22:10

ANaimi


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);
    }
}
like image 38
configurator Avatar answered Oct 17 '22 20:10

configurator