fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq.Expressions;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. // Getting types/methods
  10. var queueItemType = typeof(double);
  11. var queueType = typeof(Queue<>).MakeGenericType(queueItemType);
  12. var queueEnqueueMethod = queueType.GetMethod(nameof(Queue<object>.Enqueue), new[] { queueItemType });
  13.  
  14. // Build the Func<>
  15. var result = Expression.Parameter(queueType, "result");
  16.  
  17. var queueInstance = Expression.New(queueType);
  18. var resultAssign = Expression.Assign(result, queueInstance);
  19.  
  20. var queueItem = Expression.Constant(Convert.ChangeType(100, queueItemType), queueItemType);
  21. var addCall = Expression.Call(result, queueEnqueueMethod, queueItem);
  22.  
  23. var body = new List<Expression>
  24. {
  25. resultAssign,
  26. addCall,
  27. result // The last line in body will be the result value of the Func<>.
  28. };
  29.  
  30. var lambda = Expression.Lambda<Func<Queue<double>>>(Expression.Block(new[] { result }, body));
  31. var func = lambda.Compile();
  32.  
  33. // Call it :-)
  34. var queue = func();
  35.  
  36. Console.WriteLine(queue.Count);
  37. Console.WriteLine(queue.Dequeue());
  38. }
  39. }
Success #stdin #stdout 0.05s 134656KB
stdin
Standard input is empty
stdout
1
100