Search code examples
c#metaprogrammingexpression-treescil

How can I emulate "typeof (T)" using the System.Linq.Expressions API?


I'm trying to create a method that will create a DataTable from a list of objects using the System.Linq.Expressions API, but I can't figure out how to generate the following IL that I get when I decompile the expression typeof (int).

IL_0000:  nop         
IL_0001:  ldtoken     System.Int32
IL_0006:  call        System.Type.GetTypeFromHandle
IL_000B:  call        LINQPad.Extensions.Dump<Object>
IL_0010:  pop         
IL_0011:  ret

Currently I'm trying to skirt the problem by calling Type.GetType("System.Int") instead, but I would like to generate the code for typeof (int) if at all possible.


Solution

  • Just use Expression.Constant and pass in typeof(int) as the value:

    var expression = Expression.Constant(typeof(int), typeof(Type));
    

    That's what happens when you use typeof within a lambda expression, anyway:

    Expression<Func<Type>> func = () => typeof(T);