I was refreshing my limited knowledge of inheritance in c# 11 because I need it for a project. However I got unexpected results when calling the constructor of an inherited class. Any call to the inherited constructor always resulted in a call to base constructor first. I was under the impression that the normal way to call the base constructor before the inherited constructor is to do the following:
internal DerivedClass()
: base()
{
// Do stuff here. Behaves as expected
}
However the same functionality is achieved without the : base()
:
class Program
{
static void Main(string[] args)
{
new BaseClass(); // Prints "BaseClass". Behaves as expected
new DerivedClass(); // Prints "BaseClass"\n"DerivedClass". Expected behavior: "DerivedClass"
new DerivedClass("test"); // Prints "BaseClass"\n"test". Expected behavior: "test"
}
}
class BaseClass
{
internal BaseClass()
{
Console.WriteLine("BaseClass");
}
}
class DerivedClass : BaseClass
{
internal DerivedClass()
{
Console.WriteLine("DerivedClass");
}
internal DerivedClass(string test) // Different parameters than BaseClass()
{
Console.WriteLine(test);
}
}
So how do I call the constructor of a derived class without constructor chaining? I thank anyone answering in advance.
What I did so far:
- Confirming the described execution flow with the dotnet debugger
- Searching the web (no relevant results)
- Searching StackOverflow (no relevant results)
- Reading the Microsoft tutorial on inheritance (not useful for this problem and the publication example had ambiguity errors out of the box (it wasn't relevant to this problem anyway))
- I am currently in Italy and OpenAI blocks ProtonVPN so I currently have no access to ChatGPT