Skip to content

Instantly share code, notes, and snippets.

@pictos
Last active March 28, 2024 04:21
Show Gist options
  • Save pictos/668308692eb188279668b679f60728cd to your computer and use it in GitHub Desktop.
Save pictos/668308692eb188279668b679f60728cd to your computer and use it in GitHub Desktop.
A ref struct that will tweak values for you
new ViewModel().Run();
class ViewModel
{
private bool flag = true;
public bool Flag {get; set;} = false;
public void Run()
{
using(new HoldAndChangeValue(ref flag, () => Flag = !Flag))
{
InternalRun();
}
Console.WriteLine($"flag value is : {flag} - Inside 'Run'");
Console.WriteLine($"Flag value is : {Flag} - Inside 'Run'");
}
void InternalRun()
{
Console.WriteLine($"flag value is : {flag} - Inside 'internalRun'");
Console.WriteLine($"Flag value is : {Flag} - Inside 'Run'");
}
}
ref struct HoldAndChangeValue
{
ref bool _value;
Action _action;
public HoldAndChangeValue(ref bool value, Action action)
{
_value = ref value;
_action = action;
}
public void Dispose()
{
_value = !_value;
_action();
Console.WriteLine($"flag value is : {_value} - Inside 'HoldAndChangeValue'");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment