fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5.  
  6. public class Test
  7. {
  8. public static void Main()
  9. {
  10. // Getting types/methods
  11. var itemType = typeof(double);
  12. var repeatMethod = typeof(Enumerable).GetMethod(nameof(Enumerable.Repeat)).MakeGenericMethod(itemType);
  13.  
  14. var queueType = typeof(Queue<>).MakeGenericType(itemType);
  15. var queueCtor = queueType.GetConstructor(new[] { typeof(IEnumerable<>).MakeGenericType(itemType) });
  16.  
  17. // Build the Func<>
  18. var repeatCall = Expression.Call(repeatMethod, Expression.Constant(Convert.ChangeType(100, itemType)), Expression.Constant(1, typeof(int)));
  19. var ctorCall = Expression.New(queueCtor, repeatCall);
  20.  
  21. var lambda = Expression.Lambda<Func<Queue<double>>>(ctorCall);
  22.  
  23. // How does the result look like?
  24. Console.WriteLine(lambda.ToString());
  25.  
  26. var func = lambda.Compile();
  27.  
  28. // Call it :-)
  29. var queue = func();
  30.  
  31. Console.WriteLine(queue.Count);
  32. Console.WriteLine(queue.Dequeue());
  33. }
  34. }
Success #stdin #stdout 0.04s 134656KB
stdin
Standard input is empty
stdout
() => new Queue`1(Repeat(100, 1))
1
100