by gregmac · 3y ago · 0 comments
In C# the idiomatic way would be to have each of these 3 things be defined in a class using IDisposable, which is similar to D's scope() -- the declaring class gets a cleanup method when the variable goes out of scope, no matter how that happens.
I assume there's some interaction between these classes, but IMHO that should be explicitly defined and so the code would look something like:
public void foo(int bar) {
using var something = new Something(bar)
if (something.do()) {
using var stuff = new Stuff(bar);
if (stuff.init()) {
using var stuff2 = new Stuff2(bar); // two "stuff"s looks dumb but this is example code
if (stuff2.prepare()) {
return do_the_thing(something, stuff, stuff2, bar);
}
}
}
return null;
}
There's actually several ways to structure this code which would result in something that looks better than the above, but being example code and not knowing how `something` and `stuff` interact, it's hard to write this nicely. I'd probably aim for something much more concise like: public void foo(int bar) {
using var something = new Something(bar);
using var stuff = new Stuff(something);
using var stuff2 = new Stuff2(stuff);
return stuff2.prepare() ? do_the_thing(stuff2) : null;
}
In the above, I assume stuff2.prepare() calls everything it needs to on the dependent objects, but how I'd structure this for real entirely depends on what they're actually doing.But rest assured, your C# code is full of global state hidden on its runtime and is subject to the same kinds of errors people are discussing here.