Search code examples
c#dotpeek

C#: unpack tuple returned by method to pass it into parent constructor, or other ways to fix "ISSUE: explicit constructor call"


Decompiler (dotPeek) output:

class Base {
    public Base(int d, int e, int f) {
        // logic
        Console.WriteLine ("Base constructor");
    }
}

class Child : Base {
    public Child(string a, string b, string c) {
        // logic before explicit call, calculating d, e, f

        // ISSUE: explicit constructor call
        base.\u002Ector(d, e, f);

        // logic after explicit call
    }
}

Trying to convert it to normal c# base constructor call, but can't figure out how to unpack tuple to pass it as args to parent constructor:

class Base {
    public Base(int d, int e, int f) {
    // logic
        Console.WriteLine ("Base constructor");
    }
}

class Child : Base {
    public Child(string a, string b, string c) : base(DoWorkBeforeBaseConstructor(a, b, c)) {
        // logic after explicit call
    }

    private static (int, int, int) DoWorkBeforeBaseConstructor(string a, string b, string c) {
        // logic generating response based on params
        
        // logic before explicit call
        return (1, 2, 3);
    }
}

Solution

  • There isn't a way to do this with a tuple. If you have access to the base class, add another constructor that takes a tuple:

    public Base((int e, int f, int g) tuple) : this(tuple.e, tuple.f, tuple.g)
    {
    }
    

    However, this all looks rather hacky to me and I'm not sure what you are doing follows good SOLID principles. I would consider moving the DoWorkBeforeBaseConstructor method somewhere else and just passing in the new values into the Child class.