4

I'm learning delegates in VB.NET and am confused about delegate types. In reading about delegates, I learned that delegates are a data type that can refer to a method with a particular kind of signature. So in the same way that a String can refer to characters, a delegate can refer to a method (for instance) that takes an integer as input and returns an integer as output. But in playing around with delegates, I found that this was not the case. The code below compiles and runs--even though I don't obey the 'typing' in my delegate signature. I'm confused. Am I missing something?

Public Delegate Function myDelegate(ByVal i As Integer) As Integer' int in, rtrn int

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim md As myDelegate  'should be of type int in, rtrn int
    md = New myDelegate(AddressOf squared) 'allows assign to string in, string out
    MsgBox(md("3")) 
End Sub

Private Function squared(ByVal i As String) As String
    Return i * i
End Function
bernie2436
  • 22,841
  • 49
  • 151
  • 244
  • 6
    Do you have `Option Strict On`? – SLaks Dec 14 '11 at 15:48
  • I was going to ask the same question as @SLaks... – bhamby Dec 14 '11 at 15:49
  • [Option Strict](http://msdn.microsoft.com/en-us/library/zcd4xwzs.aspx) `On`, change it to default for VB-Projects in options-dialogbox: http://msdn.microsoft.com/en-us/library/t0k7484c.aspx – Tim Schmelter Dec 14 '11 at 15:54
  • Note to Microsoft - please default `Option Strict On` inn Visual Studio. Note to VB.NET developers - make sure you default `Option Strict On` (and switch it on for all your existing projects) – Matt Wilko Dec 14 '11 at 16:22
  • Here is how to set up option strict to default http://stackoverflow.com/questions/5160669/option-strict-on-by-default-in-vb-net – bernie2436 Dec 14 '11 at 16:41

1 Answers1

6

Yes, VB.NET is a strongly typed language, and so are delegates. But VB.NET inherits a lot of baggage from older versions of VB, such as implicit value conversion. The VB.NET compiler is emitting a call to Microsoft.VisualBasic.Conversions.ToDouble to "fix" the conflicting types.

If you put Option Strict On at the top of your .vb file, then you will see the errors that you expect.

Option Strict restricts implicit data type conversions to only widening conversions. Widening conversions explicitly do not permit any data type conversions in which data loss may occur and any conversion between numeric types and strings. For more information about widening conversions, see the Widening Conversions section.

Reference

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286
  • This article explains how the whole point of delegates is to provide strongly-typed function pointers for .NET http://codebetter.com/karlseguin/2008/11/27/back-to-basics-delegates-anonymous-methods-and-lambda-expressions/ – bernie2436 Dec 20 '11 at 01:38