Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is there not a `fieldof` or `methodof` operator in C#?
    text
    copied!<p>They could be used as follows:</p> <pre><code>FieldInfo field = fieldof(string.Empty); MethodInfo method1 = methodof(int.ToString); MethodInfo method2 = methodof(int.ToString(IFormatProvider)); </code></pre> <p><code>fieldof</code> could be compiled to IL as:</p> <pre><code>ldtoken &lt;field&gt; call FieldInfo.GetFieldFromHandle </code></pre> <p><code>methodof</code> could be compiled to IL as:</p> <pre><code>ldtoken &lt;method&gt; call MethodBase.GetMethodFromHandle </code></pre> <p>Whenever the <code>typeof</code> 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.</p> <pre><code>public static FieldInfo fieldof&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expression) { MemberExpression body = (MemberExpression)expression.Body; return (FieldInfo)body.Member; } public static MethodInfo methodof&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static MethodInfo methodof(Expression&lt;Action&gt; expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static void Test() { FieldInfo field = fieldof(() =&gt; string.Empty); MethodInfo method1 = methodof(() =&gt; default(string).ToString()); MethodInfo method2 = methodof(() =&gt; default(string).ToString(default(IFormatProvider))); MethodInfo method3 = methodof(() =&gt; default(List&lt;int&gt;).Add(default(int))); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload