Search code examples
c#constructorthismultiple-constructors

Can I call a overloaded constructor of the same class in C#?


I know that I can do that with ': this()' but if I do that the overloaded constructor will be excecuted first and I need it to be executed after the the constructor that will call it . . . . Is complicated to explain let me put some code:

Class foo{
    public foo(){
       Console.WriteLine("A");
    }
    public foo(string x) : this(){
       Console.WriteLine(x);
    }
}

///....

Class main{
    public static void main( string [] args ){
       foo f = new foo("the letter is: ");
    }
}

In this example the program will show

A 
the letter is:

but what I want is

the letter is: 
A

There is a 'elegant way' to do this? I would prefer to avoid extracting the constructor actions to separated method and call them from there.


Solution

  • Yes, you can do this pretty easily (unfortunately):

    class foo {
        public foo( ) {
            Console.WriteLine( "A" );
        }
        public foo( string x ) {
            Console.WriteLine( x );
    
            var c = this.GetType( ).GetConstructor( new Type[ ] { } );
            c.Invoke( new object[ ] { } );
        }
    }
    
    class Program {
        static void Main( string[ ] args ) {
            new foo( "the letter is: " );
        }
    }