d11
d11

Reputation: 380

why doesn't my c# base constructor get called?

public class Animal
{
    public Animal()
    {
        "animal ctor".Dump();
    }
}

public class Cat :Animal
{
    public Cat():this("gray")
    {
        "cat ctor".Dump();
    }

    public Cat(string c):base()
    {
        "cat ctor2".Dump();
    }
}

void Main()
{
    Cat a = new Cat();
}

The code's output is :

animal ctor
cat ctor2
cat ctor

I understand the first line.

The Animal Ctor is called first, but then the Cat ctor is calling the string overload public Cat(string c):base() - but this ALSO calls base's constructor.

So why I don't see animal ctor again (:base())?

Upvotes: 2

Views: 1024

Answers (3)

Selman Genç
Selman Genç

Reputation: 101681

the constructor is only called once:

  1. your Cat() constructor calls Cat(string c)
  2. Cat(string c) is calling base constructor
  3. base constructor is executed
  4. Cat(string c) is executed (which is the caller of base)
  5. Then Cat() constructor is executed

Basically if you call the base constructor (or another constructor in your class), that is executed before your constructor.See the documentation for more details

Upvotes: 5

Rowland Shaw
Rowland Shaw

Reputation: 38130

Cat() explicitly calls Cat(string) which explicitly calls Animal().

These calls happen before each method starts, so you see them dumped in reverse order.

Cat() does not call Animal() directly, meaning the base class' constructor would only be called once (which, is probably what you want)

If you don't explicitly specify which constructor to call, then the default constructor for the base class is called; So the following:

public Cat(string c) :base()
{
    "cat ctor2".Dump();
}

Is equivalent to:

public Cat(string c)
{
    "cat ctor2".Dump();
}

Upvotes: 1

Kajal Sinha
Kajal Sinha

Reputation: 1565

There are a few rules of inheritance and object construction.

Here, the constructor is called in sequence Cat() : this(string) which is Cat(string) : base() which is Animal()

Animal is base of Cat so Animal is constructed first. once Animal() constructor call is finished, then Cat(string) will complete and subsequently Cat() invocation will be completed.

Even if you do not mention base(), base will still be invoked. A parameterless constructor is always invoked by default (if available) and this process is bubbled up to the topmost parent in hierarchy.

A parameterless constructor is always present for every class. But, if you declare one with a parameter, then you explicitly need to declare a parameterless constructor.

Upvotes: 0

Related Questions