Skip to content

Instantly share code, notes, and snippets.

@jchadwick
Created December 27, 2011 17:18
Show Gist options
  • Save jchadwick/1524429 to your computer and use it in GitHub Desktop.
Save jchadwick/1524429 to your computer and use it in GitHub Desktop.
Expression helpers
using System;
using System.Linq.Expressions;
using System.Reflection;
public static class ExpressionHelpers
{
public static T GetValue<T>(this Expression<Func<T>> source)
{
T unknownValue = source.Compile().Invoke();
return unknownValue;
}
public static TProp GetValue<T, TProp>(this T source, Expression<Func<T, TProp>> property)
{
return property.Compile().Invoke(source);
}
public static string Name<T>(this Expression<Func<T>> target)
{
return (target.Body as MemberExpression).Member.Name;
}
public static string Name<T, TProp>(this T source, Expression<Func<T, TProp>> property)
{
return (property.Body as MemberExpression).Member.Name;
}
public static void SetValue<T, TProp>(this T target, Expression<Func<T, TProp>> property, TProp value)
{
var parms = new[] { property.Parameters[0], Expression.Parameter(typeof(TProp), "value") };
var expression = Expression.Call(AssignmentHelper<TProp>.MethodInfoSetValue,
new[] { property.Body, parms[1] });
var lambda = Expression.Lambda<Action<T, TProp>>(expression, parms);
var action = lambda.Compile();
action(target, value);
}
private class AssignmentHelper<T>
{
internal static readonly MethodInfo MethodInfoSetValue =
typeof(AssignmentHelper<T>).GetMethod("SetValue", BindingFlags.NonPublic | BindingFlags.Static);
private static void SetValue(ref T target, T value)
{
target = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment