Wednesday, July 25, 2007

I was looking for a way to pass a parameter by reference today.  More specifically the setter.

I found a couple interesting blog posts

http://geekswithblogs.net/akraus1/archive/2006/02/10/69047.aspx

notice the comment by Tedesco.

He offers a nice way to do this via an anonymous delegate.

public delegate void InsertString( System.String param ); public partial class Bird { public void FileToDb( int x) { FillEntityColumn(delegate( System.String value) {tExtra.Text = value; }); } }

So we actual pass the FillEntityColumn method an anonymous delegate which then sets the property.

Now in vb you can write
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        testme(TextBox1.Text)
    End Sub
    Sub testme(ByRef s As String)
        s = "hello"
    End Sub
End Class

which a commenter on http://musingmarc.blogspot.com/2006/04/tale-of-two-implementations.html eluded to.  But in vb you still cannot pass a Property by reference, at least not really.  Take a look what vb generates into il.

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim VB$t_ref$S0 As TextBox = Me.TextBox1
    Dim VB$t_string$S0 As String = VB$t_ref$S0.Text
    Me.testme((VB$t_string$S0))
    VB$t_ref$S0.Text = VB$t_string$S0
End Sub

 
As you can see vb is writing some code for you which is nice, but we are still not passing the property by ref.
   -Mike has also talked about the want of passing parameters. ( the same misguided comment that vb supports passing parameters by ref)
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview