I have a linq expression defined as follows:
private void GetMyPropertyType<T>(Expression<Func<T, object>> expression)
{
// some code
----- HERE -----
}
which is called as
GetMyPropertyType<SomeType>(x => x.Age);
Now I want to know what the type is of "Age" at the position marked as "HERE". The closest I've gotten is:"
expression.Body.Member.ToString()
which returns the value Int64 Age
that I can then split and only take the first part of. The problem however is that I want to get the full path (System.Int64
) which it only returns for certain types (like String
).
Am I missing a completely obvious method? Or should I be doing it in this very ugly fashion?
Thanks in advance for any help.
You can use Expression.Type
to find out the static type of the expression. However, because you've got Expression<Func<T, object>>
you've actually got a conversion expression around the property expression, so you need to remove that first. Here's some sample code which works for the simple cases I've tried:
using System;
using System.Linq.Expressions;
class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
class Test
{
static void Main(string[] args)
{
ShowMemberType<Person>(p => p.Age);
ShowMemberType<Person>(p => p.Name);
}
static void ShowMemberType<T>(Expression<Func<T, object>> expression)
{
var body = expression.Body;
// Unwrap the conversion to object, if there is one.
if (body.NodeType == ExpressionType.Convert)
{
body = ((UnaryExpression)body).Operand;
}
Console.WriteLine("Type: {0}", body.Type);
}
}
See more on this question at Stackoverflow