Relaxed Delegates in VB.NET 2008

0.00 avg. rating (0% score) - 0 votes

Reference: http://msdn.microsoft.com/en-gb/library/ms364068(VS.80).aspx

In VS2005 the following code cannot compile and gives an error saying that testSub does not have the signature required by the Activated event. However, in VS2008 this compiles successfully without any error!


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler
MyBase.Activated, AddressOf testSub
End Sub

Private Sub testSub()
End Sub


This is a new feature in VB 2008 called “Relaxed Delegates”; since it’s safe for a delegate with parameters to point at a method with zero parameters, we now allow this to compile. (This is called a “zero-argument relaxation”).


The following is also allowed:


Module Module1
Delegate Sub MyDelegate(ByVal x As Short)
Sub Foo(ByVal x As Integer)
MsgBox(x)
End Sub

Sub Main()
Dim d As MyDelegate = AddressOf Foo
d.Invoke(4)
End Sub
End Module


We’ve pointed MyDelegate at a method that does not have an exact signature match. This is completely safe though because when we invoke the delegate, it can only take something that can fit inside a Short variable; since Short always widens to Integer, this is completely safe and guaranteed to work at runtime.


Now if we try it the other way around (make MyDelegate of type Integer and Foo take a parameter of type Short) it’ll only work with Option Strict Off (since this conversion could fail at runtime).

However, this is not possible in C#:


private void Form1_Load(object sender, EventArgs e)
{
this.textBox1.TextChanged += new EventHandler(textBox1_TextChanged);
}
void textBox1_TextChanged(){}


This gives: “error CS0123: No overload for ‘textBox1_TextChanged’ matches delegate ‘System.EventHandler”


Similiarly the following won’t work although Int16 can always widen to In32


public delegate void SimpleDelegate(Int16 x);
public static void MyFunc(Int32 x){}

private void Form1_Load(object sender, EventArgs e)
{
SimpleDelegate simpleDelegate
= new SimpleDelegate(MyFunc);
simpleDelegate
.Invoke(9); //or simpleDelegate(9);
}


This again gives a similiar error message:


“No overload for ‘WindowsFormsApplication2.Form1.MyFunc(int)’ matches delegate ‘WindowsFormsApplication2.Form1.SimpleDelegate'”


Relaxed delagates is not supported in C#. However, both C# and VB have another ‘version’ of relaxed delegates – you can use type ‘object’ for any of the parameters

0.00 avg. rating (0% score) - 0 votes
ToughDev

ToughDev

A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>