Reputation: 3120
how can I convert the following code from C# to VB without exposing "variable" as global variable.
private void SomeMethod(SomeType variable)
{
this.SomeEvent+= delegate
{
if (variable == 1)
{
this.DoSomething();
}
}
//here I have some other code
}
Upvotes: 0
Views: 346
Reputation: 9050
One possible solution
Private Sub SomeMethod(ByVal variable As Integer)
AddHandler Me.SomeEvent,
Sub()
If (variable = 1) Then
Me.DoSomething()
End If
End Sub
Console.WriteLine("ciao")
End Sub
I just tried that and it works like a charm, so i don't know why u say it doesnt :( Visual studio 2010.
You can also do something like this
Private Sub SomeMethod(ByVal variable As Integer)
Me.SomeEvent = DirectCast(Delegate.Combine(Me.SomeEvent, Sub()
If (variable = 1) Then
Me.DoSomething
End If
End Sub), MyDelegate)
...mycode
End Sub
Delegate.Combine have exactly the same effect as AddHandler.
I don't have visual studio 2008 so I don't know how to write that in VS2008, try the second solution, the first seems to work only on 2010.
If this doesn't work you can try this out, more code to write:
Public Delegate Sub MyDelegate()
Public Class Class1
Public Event SomeEvent As MyDelegate
Private Class MyDelegateClass
Public Owner As Class1
Public Variable As Integer
Public Sub Method()
If (Variable = 1) Then
Owner.DoSomething()
End If
End Sub
End Class
Private Sub SomeMethod(ByVal variable As Integer)
Dim dc As New MyDelegateClass
dc.Owner = Me
dc.Variable = variable
AddHandler Me.SomeEvent, AddressOf dc.Method
Console.WriteLine("ciao")
End Sub
Public Sub DoSomething()
Console.WriteLine("hello")
End Sub
End Class
Visual studio syntactic sugar does something like this with anonymous delegate.
Upvotes: 4