1

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.

4
  • 1
    I doubt that's possible. What's wrong with passing it as an argument ? Commented Mar 29, 2023 at 9:10
  • Nah, that's not possible. You'd have to pass a reference to Foo into A and then into B. Commented Mar 29, 2023 at 9:11
  • @wohlstad The example above is a simple one but imagine long call chains, imagine that inside each method you have many other function calls, imagine that those methods already have some other arguments and you want anywhere down the call chain to know the surrounding using blocks. Commented Mar 29, 2023 at 9:24
  • 1
    Passing the Foo instance via parameters is the cleanest and most maintainable solution. If you end up forwarding it through a chain of methods and only the deepest call actually uses it then you might want to rethink your design. Unfortunately there is no magic bullet to solve this problem. Commented Mar 29, 2023 at 9:40

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.