More IL features missing from C#
April 20, 2009 at 09:30 PM | categories: Uncategorized | View Comments Wesner Moise wrote about IL features missing in C#: extended precision for floating-point calculations, and tail call optimizations. His post reminded me of a few more IL features that could be useful in C# but that aren't exposed or aren't documented.ldtoken
: This is the opcode behind typeof
. ldtoken
also operates on fields and methods, opening up the possibility of hypothetical fieldof
and methodof
keywords: these might return FieldInfo
and MethodInfo
objects at runtime respectively, allowing you to write reflection code that's checked at compile time.
There is in fact a trick you can use to get hold of a MethodInfo
object without having to call Type.GetMethod
or the like:
MethodInfo methodInfo = new Action<string>(Console.WriteLine).Method;
However, because this trick instantiates a new delegate to use its Method
property, it's only useful when:
- You're dealing with static methods
- You have an instance of the right type
Note that this trick doesn't work on property accessors, since there's no delegate syntax for these like there is for methods.
Typed references: You may have noticed the System.TypedReference
class documented in MSDN, and wondered what it was useful for. C# supports typed references -- effectively safe, verifiable pointers -- via three undocumented keywords.
int i = 42; TypedReference reference = __makeref(i); Debug.Assert(__reftype(reference) == typeof(int)); Debug.Assert(__refvalue(reference, int) == 42);
I haven't seen any official statement from Microsoft saying that this technique is going to stop working any time soon, but they don't seem to be in a hurry to fix bugs relating to these keywords.