MyClass.cs:
namespace ConsoleApp
{
public partial class MyClass
{
public string Name { get; set; }
public MyClass()
{
Name = "base";
}
}
}
MyClass2.cs:
namespace ConsoleApp
{
public partial class MyClass
{
public MyClass(string nothing) : base()
{
}
}
}
Program.cs:
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
MyClass myClass = new("str");
Console.WriteLine(myClass.Name);
}
}
}
When I run this program, myClass.Name was not set by the base constructor. I put a breakpoint in the parameterless constructor is it was not called from the parameter'ed constructor. Any idea if this is allowed? If so, what did I miss?
Thanks!
If you want your constructor with parameters to invoke another one in the same object you should use this
keyword, not base
:
public MyClass(string nothing) : this()
{
}
In your code base
will invoke parameterless constructor of base class which is System.Object
.