Calling a constructor from another constructor in the same class

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 name one constructor from another using the above approach. But in this case, if I call constructor 2, all instructions in constructor 1 will be executed BEFORE the statement itself is executed in constructor 2.

I want that after all the statements in constructor 2 are executed, it is called by constructor 1.

In my exact situation, I am performing user authentication. Constructor 1 retrieves user information with only the user ID, but constructor 2 authenticates the user using email and password. If the user is in the database, he gets the user ID, and now I want constructor 1 to populate all the properties of the class.

Please let me know if you need more information. If you think there is another better approach, I would be glad to hear 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 } 
+7
source share
5 answers

In this case, just don't use the constructor calls, but something like:

 public class FooBar() { public FooBar(string s) { Init1(); } public FooBar(int i) { Init2(); Init1(); } } 

Where I assumed that Init1(..) and Init2(..) are methods associated with some specific initialization logic of the corresponding constructor.

In fact, you can organize these function calls in a way that suits your needs.

+7
source

You can use another private method to initialize:

 public class FooBar() { public FooBar(string s) { this.Initialize(s); } public FooBar(int i) { this.Initialize("My String"); } private void Initialize(string s) { // Do what constructor 1 did } } 
+8
source

Why not wrap this functionality in some method and call it in the constructors (or wherever you want)?

 public class FooBar() { public FooBar(string s) { LoadUser(s); } public FooBar(int i) : this("My String") { var s=CheckUser(); LoadUser(s); } private string CheckUser() { return "the id/name from db"; } private void LoadUser(string s) { //load the user } } 

This is a common solution. You can change the return type to suit your specific scenario.

+2
source

In general, you can use this:

 public class FooBar() { private Test(string s) { // Some functionality } public FooBar(string s) { Test(s); } public FooBar(int i) { // Do what you need here Test("MyString"); } } 
+2
source

The best approach is do not put this logic in the constructor. Divide it into other methods that you can call as you wish without worrying about the chain of constructors.

+1
source

All Articles