EDIT: So it looks like the only way to do this is with IDisposable. I suspected as much but it's still a bit of a bummer. I may make a class for this that takes an Action as @mjwills suggests but I still personally wish there was a way to do this without the using block. Alternative syntax like "using (var foo = new Bar([action]);" that makes the using statement apply to the block it's called from would be great.
In C# is it possible to perform an action when a variable goes out of scope? In C++ I would use an object's destructor to do something when it goes out of scope, but the garbage collector means I can't (cleanly) get the same behavior in C#. This is what I would write in C++:
class SetOnDestruction
{
bool& m_thingToSet;
bool m_newValueForThing;
public:
SetOnDestruction(bool& thingToSet, bool newValueForThing)
: m_thingToSet(thingToSet)
, m_newValueForThing(newValueForThing)
{
}
~SetOnDestruction()
{
m_thingToSet = m_newValueForThing;
}
};
void ExampleUsage()
{
bool thingToSet = true;
{
SetOnDestruction setter(thingToSet, false);
// do some stuff here
}
// thingToSet should now be false
}
I don't want to use IDisposable because then I'm wrapping my functions in big using blocks for what is really just a bit of syntactic sugar.
Does anyone know of anything relevant?