I have a class with two constructors (C#). Here is the code snippet:
public class FooBar()
{
public FooBar(string s)
{
// constructor 1, some functionality
}
public FooBar(int i) : this("My String")
{
// constructor 2, some other functionality
}
}
Yes, I know that I can call one constructor from another using the above mentioned approach. But in this scenario, if I call constructor 2, all statements in constructor 1 will run BEFORE the very statement in constructor 2 is executed.
What I want is that after all statements in constructor 2 are run, then it will call constructor 1.
In my exact situation, I am doing user authentication. Constructor 1 retrieves user information with just the user ID, but constructor 2 does the user authentication using email and password. If a user is in the database, it gets the user ID and now I want constructor 1 to populate all properties of the class.
Please let me know if you require additional information. If you think that there is another better approach, I would be happy to listen the suggestion.
UPDATE 1: I wonder why something like this is not implemented:
public FooBar(bool b)
{
// constructor 3, some more functionality
this.FooBar("My String"); // calling constructor 1
}
In general you could use this:
In this case just do not use constructor calls, but something like :
Where I supposed that
Init1(..)
andInit2(..)
are methods related to some specific intialization logic of corresponding constructor.Actually you can arrange this function calls in a way that better fits your needs.
Best approach - don't put that logic in the constructor. Break it out to other methods that you can call at will without worrying about constructor chaining.
You can use another private method to do the initialization:
Why not wrap that functionality into some
method
and call that in the constuctors (or wherever you want) ?This is a generic solution. You may change the return type according to your specific scenario.