Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 790
Kyle Sletten Avatar asked Sep 13 '25 17:09

Kyle Sletten


1 Answers

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);
like image 54
Jon Skeet Avatar answered Sep 16 '25 09:09

Jon Skeet