Default Constructors
I stumbled across an interesting thing this morning with C# and default constructors.
Take the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
class Vehicle
{
public Vehicle()
{
Console.WriteLine("New Vehicle");
}
}
class Car : Vehicle
{
public Car()
{
Console.WriteLine("New Car");
}
}
class EntryPoint
{
public static void Main(string[] args)
{
Car car = new Car();
}
}
My question is why would the Vehicle default constructor be called even though Ive created a default constructor for Car that does not call base? Even more interesting is that when I change Car’s signature to take a parameter, then the code doesnt even compile.
This post is licensed under CC BY 4.0 by the author.