Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call one constructor from the body of another in C#

Tags:

c#

constructor

I need to call one constructor from the body of another one. How can I do that?

Basically

class foo {     public foo (int x, int y)     {     }      public foo (string s)     {         // ... do something          // Call another constructor         this (x, y); // Doesn't work         foo (x, y); // neither     } } 
like image 207
tom Avatar asked Sep 27 '11 21:09

tom


People also ask

How do you call one constructor from another?

Example 1: Java program to call one constructor from another Here, you have created two constructors inside the Main class. Inside the first constructor, we have used this keyword to call the second constructor. this(5, 2); Here, the second constructor is called from the first constructor by passing arguments 5 and 2.

Can a constructor be called from another class?

No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.

Can we call one constructor from another in C++?

No, in C++ you cannot call a constructor from a constructor.

Which method call a constructor in another constructor?

Constructor chaining is the process of calling one constructor from another constructor with respect to current object.


1 Answers

You can't.

You'll have to find a way to chain the constructors, as in:

public foo (int x, int y) { } public foo (string s) : this(XFromString(s), YFromString(s)) { ... } 

or move your construction code into a common setup method, like this:

public foo (int x, int y) { Setup(x, y); } public foo (string s) {    // do stuff    int x = XFromString(s);    int y = YFromString(s);    Setup(x, y); }  public void Setup(int x, int y) { ... } 
like image 83
ladenedge Avatar answered Sep 26 '22 08:09

ladenedge