C# Get type of property specified in Action

808 views Asked by At

I must create similar to Fluent API. I have DTO: public class Foo { public string Bar {get;set;} }

And i need to provide some properties (for example column name):

new MyFluentApi<Foo>().ColumnAttributes(**p => p.Bar**).ColumnName("Some very long column name where are Bar values")

In ColumnAttributes i need to get Type/name of specified property, but how? In expression p => p.Bar i get actual value of Bar, but i need type

1

There are 1 answers

4
Johnathan Barclay On

Like this:

public static MyFluentApi<T> ColumnAttributes<T>(this MyFluentApi<T> api,
    Expression<Func<T, object>> selector)
{
    var expression = (MemberExpression)selector.Body; // Assume expression is accessing a member of T
    var prop = (PropertyInfo)expression.Member; // Assume said member is a property
    var type = prop.PropertyType; // Get the type of property

    // Do something with type

    return api;
}

Note that if your lambda isn't a straight property access this will throw an exception.

An alternative would be to use type inference:

public static MyFluentApi<T> ColumnAttributes<T, TProp>(this MyFluentApi<T> api,
    Expression<Func<T, TProp>> selector)
{
    var type = typeof(TProp);

    // Do something with type

    return api;
}

Now this should work with any expression, regardless as to whether a property is accessed, which may or may not be what you're after.

For example, this would run without exception:

new MyFluentApi<Foo>().ColumnAttributes(p => new object());