-3

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!

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Johnny Wu
  • 1,297
  • 15
  • 31
  • 2
    It seems you're mixing inheritance with partial classes. – Alessandro D'Andria Jun 15 '21 at 17:46
  • 4
    ` : base()` this is calling `Object` constructor (the base class). – Alessandro D'Andria Jun 15 '21 at 17:47
  • 5
    You should be using `: this()`, not `: base()`. – Peter Duniho Jun 15 '21 at 17:53
  • I hope this article can remain available...though it's closed. Sometime, it's not what you know or don't know, but what you think you know is actually not what is. Google can only be helpful when you ask the "right" question. Kind of like spell checker, it wouldn't tell you about your semantic error. Not everyone has access to a support group to help w/ this kind topic. That's why stackoverflow is so valuable. Thanks to everyone who helped w/ this question. – Johnny Wu Jun 16 '21 at 11:49

1 Answers1

2

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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132