Understanding Generics—Simulating Generic Delegates Under .NET 1.1
Simulating Generic Delegates Under .NET 1.1
As you can see, generic delegates offer a more flexible way to specify the method to be invoked.
Under .NET 1.1, you could achieve a similar end result using a generic System.Object:
public delegate void MyDelegate(object arg);
Although this allows you to send any type of data to a delegate target, you do so without type safety and with possible boxing penalties. For instance, assume you have created two instances of MyDelegate, both of which point to the same method, MyTarget. Note the boxing/unboxing penalties
as well as the inherent lack of type safety:
class Program { static void Main(string[] args) { ... // Register target with 'traditional' //delegate syntax. MyDelegate d = new MyDelegate(MyTarget); d("More string data"); // Register target using method group conversion. MyDelegate d2 = MyTarget; d2(9); // Boxing penalty. ... } // Due to a lack of type safety, we must // determine the underlying type before casting. static void MyTarget(object arg) { if(arg is int) { int i = (int)arg; // Unboxing penalty. Console.WriteLine("++arg is: {0}", ++i); } if(arg is string) { string s = (string)arg; Console.WriteLine("arg in uppercase is: {0}", s.ToUpper()); } } }
When you send out a value type to the target site, the value is (of course) boxed and unboxed once received by the target method. As well, given that the incoming parameter could be anything at all, you must dynamically check the underlying type before casting. Using generic delegates, you can still obtain the desired flexibility without the "issues."
|

