Thursday 10 July 2008

C# delegates

A quick note on c# delegate functions:

I found the standard way to define delegates a little clumsy and verbose in some situations, for example when wanting to pass a function to a .Invoke method of a control to add it to its thread work queue. In this situation the delegate's purpose is really just to pass the method to the invoker, there is no other use of the delegate so declaring it at class level is a much wider scope that I would like. What I wanted is a more terse, compact and locally scoped way to achieve the same thing, here it is:

The simple way:

Declare delegate within class, e.g.

public delegate void updateStockView(Stock[] stocks);

use to create a new delegate instance to pass to invoke on a control, e.g.

instrumentDgv1.Invoke(new updateStockView(this.updateStockView), new object[] {instrumentResponse.Stocks});

This approach, whilst perfectly valid feels a little cumbersome. Firstly the delegate is at an uneccessarily high level of scope, secondly, the statment requires a new instance of the delegate to be created, passing the delegate's parameters down as an object array.

A more compact form:

instrumentDgv1.Invoke((MethodInvoker)delegate { this.updateStockView(instrumentResponse.Stocks); });

Here we see, no unnecessary declaration of the delegate type, no creation of the delegate instance, no passing of parameters as an object array - all round much tighter syntax for this type of use.

The key thing to make this work is the MethodInvoker cast. MethodInvoker is from the System.Windows.Forms namespace and is used to cast the existing method to the delegate type without requiring the declaration/instantiation of a new delegate.

.

1 comment:

Dev Singh said...

i like this post

www.richonet.com
www.bwtrp.com
www.oracledba.in