Why is there not a `fieldof` or `methodof` operator in C#?

c#, reflection

Solution

Eric Lippert (on the C# design team) has an excellent overview/discussion on this topic here. To quote:

It’s an awesome feature that pretty much everyone involved in the design process wishes we could do, but there are good practical reasons why we choose not to. If there comes a day when designing it and implementing it is the best way we could spend our limited budget, we’ll do it. Until then, use Reflection.

Problem

They could be used as follows: ``` FieldInfo field = fieldof(string.Empty); MethodInfo method1 = methodof(int.ToString); MethodInfo method2 = methodof(int.ToString(IFormatProvider)); ``` `fieldof` could be compiled to IL as: ``` ldtoken <field> call FieldInfo.GetFieldFromHandle ``` `methodof` could be compiled to IL as: ``` ldtoken <method> call MethodBase.GetMethodFromHandle ``` Whenever the `typeof` operator is used, you get perfect Find All References results. Unfortunately, as soon as you go to fields or methods, you end up with nasty hacks. I think you could do the following... or you can go back to getting a field by name. ``` public static FieldInfo fieldof<T>(Expression<Func<T>> expression) { MemberExpression body = (MemberExpression)expression.Body; return (FieldInfo)body.Member; } public static MethodInfo methodof<T>(Expression<Func<T>> expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static MethodInfo methodof(Expression<Action> expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static void Test() { FieldInfo field = fieldof(() => string.Empty); MethodInfo method1 = methodof(() => default(string).ToString()); MethodInfo method2 = methodof(() => default(string).ToString(default(IFormatProvider))); MethodInfo method3 = methodof(() => default(List<int>).Add(default(int))); } ```

Original source

Related problems