Setting a property via anonymous delegates

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

    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

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)
Comments [1]
Thursday, 15 October 2009 13:19:07 (Pacific Standard Time, UTC-08:00)
Your code is hard to read, black-on-black is only readable when you select the code with the mouse.

Anyway, all I wanted to say is that you are absolutely right: all you do is passing a string by reference (as with ref params in C#), which makes sense if you want to change the variable holding the parameter in the calling code. But when this is a temporary variable (as the result of a property-get call, like in this case) this doesn't work: the temporary variable will be changed but on return of the method, the variable is discarded. Textbox1.Text will remain the same.
All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
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