using System.Linq.Expressions;
using System.Collections.Generic;
private static void GetDefinitionFromExpression<TConf, TArg>(
Expression<Func<TConf, TArg>> getExpr)
var body = getExpr.Body as MemberExpression;
if (body != null && body.NodeType == ExpressionType.MemberAccess)
var prop = (PropertyInfo)(body).Member;
Console.WriteLine(prop.Name);
var methodBody = getExpr.Body as MethodCallExpression;
if (methodBody != null && methodBody.NodeType == ExpressionType.Call)
var getter = methodBody.Method;
if (!getter.Name.StartsWith("get_") && getter.IsSpecialName)
throw new InvalidOperationException(
"The only method call expressions allowed are indexer-gets.");
var setMethodName = "set" + getter.Name.Substring("get".Length);
var declaringType = getter.DeclaringType;
if (declaringType == null)
throw new InvalidOperationException(String.Format(
"Cannot find declaring type for getter {0}.",
var setter = declaringType.GetTypeInfo().GetMethod(setMethodName);
var arg = methodBody.Arguments[0];
if (arg is ConstantExpression)
name = (arg as ConstantExpression).Value;
Console.WriteLine($"Name: {name}");
throw new InvalidOperationException();
public static void Main()
GetDefinitionFromExpression<DateTime, int>(dt => dt.Day);
GetDefinitionFromExpression<Dictionary<string, string>, string>(dict => dict["hello world"]);