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

    Question

  • 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#?

    Wednesday, December 14, 2005 3:35 PM

Answers

  • 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.
    Wednesday, December 14, 2005 4:19 PM