Is it possible to call an overloaded constructor of the same class in C #?

I know that I can do this with: :(), but if I do this, the overloaded constructor will be processed first, and I need it to be executed after the constructor that will call it., It’s difficult to explain, let me add code to me:

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 I want

the letter is: 
A

Is there an "elegant way"? I would prefer not to extract the constructor actions into a separate method and call them from there.

+3
source share
2 answers

Yes, you can do this quite 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: " );
    }
}
+2

Retrieve the constructor actions for the virtual methods and call them from there.

, .

0

All Articles