Created
August 12, 2010 17:18
-
-
Save jonfuller/521305 to your computer and use it in GitHub Desktop.
Change a value atomically, then set it back after some operation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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