Earlz
Earlz

Reputation: 63835

Why is the base() constructor not necessary?

I have a class structure like

abstract class Animal {
  public Animal(){
    //init stuff..
  }
}

class Cat : Animal {
  public Cat(bool is_keyboard) : base() //NOTE here
  {
    //other init stuff
  }
}

Now then, look at the noted line. If you remove : base() then it will compile without an error.

Why is this? Is there a way to disable this behavior?

Upvotes: 8

Views: 898

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

17.10.4 Default Constructors:

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. 2 That default constructor simply invokes the parameterless constructor of the direct base class. 3 If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. 4 If the class is abstract then the declared accessibility for the default constructor is protected. 5 Otherwise, the declared accessibility for the default constructor is public

Upvotes: 1

SDReyes
SDReyes

Reputation: 9954

Why is this?

This article explains it.

Is there a way to disable this behavior?

Nope. I'm sorry (but ... See mark answer for a workaround : )

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

There is an implicit : base() if you don't add anything else (any : base(...) or : this(...)). To force it to be explicit, add a parameter to the base-constructor(s). Then it can't be implicit.

For example:

public Animal(string name) {...}

Upvotes: 7

Related Questions