Default Constructor

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Constructors and Finalizers:
* Default Constructor

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
38 Constructors and Finalizers
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script