Mega Code Archive

 
Categories / C# Book / 09 Reflection
 

0621 Instantiate generic types

To dynamically instantiate a delegate, call Delegate.CreateDelegate. The following example demonstrates instantiating both an instance delegate and a static delegate: using System; using System.Reflection; using System.Collections.Generic; class Program { delegate int IntFunc(int x); static int Square(int x) { return x * x; } // Static method int Cube (int x) { return x * x * x; } // Instance method static void Main() { Delegate staticD = Delegate.CreateDelegate(typeof(IntFunc), typeof(Program), "Square"); Delegate instanceD = Delegate.CreateDelegate (typeof(IntFunc), new Program(), "Cube"); Console.WriteLine(staticD.DynamicInvoke(3)); // 9 Console.WriteLine(instanceD.DynamicInvoke(3)); // 27 } } The output: 9 27