C# Language Constructors and Finalizers Default Constructor

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any C# Language Question?