Identify the encompassing using block

37 Views Asked by At

How can I identify down the call chain the encompassing using block? I mean without saving in a static or global the object created by using block nor passing it around. If I have:

using(new Foo())
{
    A();
}
void A()
{
    B();
}

inside function B I want to be able to identify and access Foo instance. It would be even nicer to get also the upper encompassing using block if any and so on.

1

There are 1 best solutions below

0
Marc Gravell On

There is no magic way to get ambient state, especially if you explicitly preclude things like static / async-local variables.

So: just pass it in. If B needs to know the Foo, then: B needs to know the Foo; don't make that magic - make it explicit and simple by passing it in:

using (Foo foo = new())
{
    A(foo);
}


void A(Foo foo) => B(foo);

(yes, I realize you also said "nor passing it around", but IMO that's the most appropriate solution)