Call one constructor from the body of another in C#

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) { ... }

this(x, y) is right, but it has to be before the start of the constructor body:

public Foo(int x, int y)
{
    ...
}

public Foo(string s) : this(5, 10)
{
}

Note that:

  • You can only chain to one constructor, either this or base - that constructor can chain to another one, of course.
  • The constructor body executes after the chained constructor call. There is no way to execute the constructor body first.
  • You can't use this within the arguments to the other constructor, including calling instance methods - but you can call static methods.
  • Any instance variable initializers are executed before the chained call.

I have a bit more information in my article about constructor chaining.


To call both base and this class constructor explicitly you need to use syntax given below (note, that in C# you can not use it to initialize fields like in C++):

class foo
{
    public foo (int x, int y)
    {
    }

    public foo (string s) : this(5, 6)
    {
        // ... do something
    }
}

//EDIT: Noticed, that you've used x,y in your sample. Of course, values given when invoking ctor such way can't rely on parameters of other constructor, they must be resolved other way (they do not need to be constants though as in edited code sample above). If x and y is computed from s, you can do it this way:

public foo (string s) : this(GetX(s), GetY(s))

Tags:

C#

Constructor