Skip to content

Instantly share code, notes, and snippets.

@jonfuller
Created August 12, 2010 17:18
Show Gist options
  • Save jonfuller/521305 to your computer and use it in GitHub Desktop.
Save jonfuller/521305 to your computer and use it in GitHub Desktop.
Change a value atomically, then set it back after some operation
public class Meh
{
public static void Change<TObj, TProp>(this TObj obj, Expression<Func<TObj, TProp>> propertyExpr, TProp newValue, Action operation)
{
var name = ((MemberExpression)propertyExpr.Body).Member.Name;
var prop = typeof(TObj).GetProperty(name);
var oldValue = prop.GetValue(obj, new object[0]);
try
{
prop.SetValue(obj, newValue, new object[0]);
operation();
}
finally
{
prop.SetValue(obj, oldValue, new object[0]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment