Calling another constructor (of the same object) from within a constructor

Here is the problem:

I am using a Windows.Form with multiple constructors.

Rather than repeating code all over the place, I want to call one of those constructors from another constructor:

class doSomething
{
   public doSomething( string title ) {}
   public doSomething( string title, string somethingElse )
   {
      doSomething( title );
      // do other work
   }
}

Of course if this compiled correctly, I wouldn't have had to post it!

What is the correct way to accomplish this with C#




Answer this question

Calling another constructor (of the same object) from within a constructor

  • Terry Coatta

    Try this syntax:

    class doSomething
    {
       public doSomething( string title ) {}
       public doSomething( string title, string somethingElse ) : this(title)
       { 
          // do other work
       }
    }

    You can also use the base keyword to select the constructor to use in base class.

  • Calling another constructor (of the same object) from within a constructor