When a type is defined without a constructor:
public class Animal
{
}
then the compiler generates a default constructor equivalent to the following:
public class Animal
{
public Animal() {}
}
The definition of any constructor for the type will suppress the default constructor generation. If the type were defined as follows:
public class Animal
{
public Animal(string name) {}
}
then an Animal
could only be created by calling the declared constructor.
// This is valid
var myAnimal = new Animal("Fluffy");
// This fails to compile
var unnamedAnimal = new Animal();
For the second example, the compiler will display an error message:
'Animal' does not contain a constructor that takes 0 arguments
If you want a class to have both a parameterless constructor and a constructor that takes a parameter, you can do it by explicitly implementing both constructors.
public class Animal
{
public Animal() {} //Equivalent to a default constructor.
public Animal(string name) {}
}
The compiler will not be able to generate a default constructor if the class extends another class which doesn't have a parameterless constructor. For example, if we had a class Creature
:
public class Creature
{
public Creature(Genus genus) {}
}
then Animal
defined as class Animal : Creature {}
would not compile.