Chaining Class Constructors at the end

Viewed 36

I have some old code from someone else that I need to fix so it builds again and one issue that I don't know how to fix, is constructor chaining. It looks something like this:

class Foo(){

  public Foo()
  {
    int i = /*block of code*/;
    this (i);
  }

  public Foo(int i)
  {
    //..
  }
}

The error comes at the this (i); line where it says Method, delegate, or event is expected. Basically it no longer allows you to use this as just a constructor anymore. Maybe it did in older version of C#.

What would be the appropriate way to fix this? I can replace public Foo() with public Foo(): this(i) but then it doesn't recognize the variable i anymore.

1 Answers

If you want to run a block of code before calling this(), you can use a static method:

class Foo()
{
    public Foo() : this(SomeMethod())
    {
    }

    public Foo(int i)
    {
        //..
    }

    private static int SomeMethod()
    {
        int i = /*block of code*/;
        return i;
    }
}

Note that you can't mutate the instance state in SomeMethod(), but such logic should probably be in Foo(int i) anyway.

Related