There’s been some debate on the Eric Lippert blogs (Blog post: In foof We Trust) since there is no equivalent of the typeof() operator for other kinds of code elements. Well, in my current work recently I needed such operator like methodof(…) that would return a MethodInfo, propertyof(…), constructorof(…) fieldof(…) etc… I found a pretty elegant solution on stackoverflow Why is there not a `fieldof` or `methodof` operator in C#?. I found the solution so elegant that I wanted to share it in a blog post. So basically I defined this small class:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
internal static class LinqOp {
internal static MethodInfo MethodOf<T>(Expression<Func<T>> expression) {
var body = (MethodCallExpression)expression.Body;
return body.Method;
}
internal static MethodInfo MethodOf(Expression<Action> expression) {
var body = (MethodCallExpression)expression.Body;
return body.Method;
}
internal static ConstructorInfo ConstructorOf<T>(Expression<Func<T>> expression) {
var body = (NewExpression)expression.Body;
return body.Constructor;
}
internal static PropertyInfo PropertyOf<T>(Expression<Func<T>> expression) {
var body = (MemberExpression)expression.Body;
return (PropertyInfo)body.Member;
}
internal static FieldInfo FieldOf<T>(Expression<Func<T>> expression) {
var body = (MemberExpression)expression.Body;
return (FieldInfo)body.Member;
}
}
// Sample usage
class Program {
static void Main() {
var methodInfo = LinqOp.MethodOf(() => default(List<int>).Add(default(int)));
var ctorInfo = LinqOp.ConstructorOf(() => new List<int>());
var fieldInfo = LinqOp.FieldOf(() => String.Empty);
var propertyInfo = LinqOp.PropertyOf(() => default(String).Length);
}
}
The magic comes from the fact that the usage of Expression<T> forces the C# compiler to emit an Expression each times the operators are used.
Btw, my friend Jb Evain proposed recently another hack to solve the same infoof problem by directly modifying IL code: parameterof, propertyof, methodof