If you don’t define any constructors in a class, the compiler automatically generates a default parameterless constructor. You can then create a new instance of the object without passing any parameters.
1
| Dog d1 = new Dog(); |
If you define at least one constructor, the compiler no longer generates a parameterless constructor.
Below, we define a single constructor for Dog, accepting a name parameter.
1
2
3
4
5
6
7
8
9
10
11
| public class Dog{ public string Name { get; set; } public int Age { get; set; } public Dog(string name) { Name = name; Age = 1; }} |
Now we can define a new instance of Dog by passing in a name parameter. But we can no longer create a new instance using no parameters.
1
2
3
4
5
| Dog d1 = new Dog("Rin Tin Tin");// Compiler error: Dog does not contain a constructor// that takes 0 arguments.Dog d2 = new Dog(); |

