using System.Linq.Expressions;
public static void Main()
Console.WriteLine("*** Regular nullable DateTime ***");
Console.WriteLine(GetPropertyInfo<TestClass, DateTime?>(x => x.DtNullable, default(DateTime?)));
Console.WriteLine("\n*** Conversion of DateTime to nullable DateTime ***");
Console.WriteLine(GetPropertyInfo((TestClass x) => x.Dt, default(DateTime?)));
public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> expression)
switch (expression.Body.NodeType)
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var ue = expression.Body as UnaryExpression;
Console.WriteLine("Expression body type" + expression.Body.GetType());
Console.WriteLine("Unary expression: " + ue != null);
me = ((ue != null) ? ue.Operand : null) as MemberExpression;
me = expression.Body as MemberExpression;
throw new InvalidOperationException("Expression does not refer to a property: " + expression.ToString());
return (PropertyInfo)me.Member;
public static PropertyInfo GetPropertyInfo<T, TProp>(Expression<Func<T, TProp>> expression, TProp myVal)
Console.WriteLine("Value parameter: " + typeof(TProp));
return GetPropertyInfo(convertToObjectExpression(expression));
private static Expression<Func<T, object>> convertToObjectExpression<T, TProp>(Expression<Func<T, TProp>> expression)
return Expression.Lambda<Func<T,object>>(
Expression.Convert(expression.Body, typeof(object)),
public DateTime Dt { get; set; }
public DateTime? DtNullable { get; set; }