let's say I have the following code (I need to include this snippet anywhere in a more complex expression).
Type paraType = typeof(MyModel);
var member = paraType.GetMember("BlaBla");
MemberExpression myExp = l.Expression.MakeMemberAccess(incidentParameter, member[0]);
I already know that MyModel has a member called BlaBla. I'm looking for a more elegant way to reflect this already known member.
In the sample I reflect the method by its name "BlaBla" as string and pass the MethodInfo to MakeMemberAccess. But I don't like it because it's error prone to refactoring such as renaming. If anybody (including me) renames the property "BlaBla", he will most probably forget to rename this reflection string as well.
I'm out for something similar to the typeof operator:
typeof(MyClass) -> returns a Type obejct. If I rename "MyClass", I have no problem as the reference will be automatically renamed as well.
regards
Andreas
I often use something like this to get the name of a member:
// <summary>
// Return the name of a static or instance property from a property access lambda expression.
// </summary>
// <typeparam name="T">Type of the property.</typeparam>
// <param name="propertyLambdaExpression">A lambda expression that refers to a property, in the
// form: '() => Class.Property' or '() => object.Property'</param>
// <returns>Return the name of the property represented by the provided lambda expression.</returns>
internal static string GetPropertyName<T>(System.Linq.Expressions.Expression<Func<T>> propertyLambdaExpression)
{
var me = propertyLambdaExpression.Body as System.Linq.Expressions.MemberExpression;
if (me == null) throw new ArgumentException("The argument must be a lambda expression in the form: '() => Class.Property' or '() => object.Property'");
return me.Member.Name;
}
Then you can use it like this:
Type paraType = typeof(MyModel);
var member = paraType.GetMember(GetPropertyName(() => MyModel.BlaBlah));
Note: As with anything, if your member is not static, you must have an instance to call it on, e.g. GetPropertyName(() => myModelInstance.BlaBlah)
.
UPDATE: C#6.0 (VS 2015) added this functionality natively via the nameof
operator. Hooray!