I am trying to pass a member reference to a parameter of another method. It’s a lazy loader property that initializes on first reference (see Name property in code example). The goal is to be able to pass the reference of the Name property to the GetName() method without its Get accessor being evaluated as it’s passed through. Instead, I want to reference it deeper in the stack so that its Get accessor is triggered at that point.
I am getting closer to figuring this out after happening up Actions. In my below code, I have the code GetName(Function() (Name)) which passes the property reference to GetName(). Within GetName()‘, I have the line Name.Invoke(). I know this works because the breakpoint I put in the get accessor is not tripped as its passed through the method. It’s only invoked when I call .Invoke(). However, I need to be able to return the value of the Name property as the string it returns rather than just trigger it without returning anything.
Also, while this is in VB, I am also fluent in c#, but I might ask questions about the VB.NET-equivalent syntax.
Class TestClass
Private _Name As String
Private ReadOnly Property Name As String
Get
If _Name Is Nothing Then _Name = "Bob"
Return _Name
End Get
End Property
Sub AccessPropertyValue()
GetName(Function() (Name))
End Sub
Sub GetName(Name As Action)
Name.Invoke()
End Sub
End Class
Update: Thanks to ChaosPandion, I was able to do this:
Sub AccessPropertyValue()
Dim s As String = GetName(Function() (Name))
End Sub
Function GetName(Name As Func(Of String)) As String
Return Name.Invoke()
End Function
I hope this helps others.
You’ll want to use
System.Func(Of String)rather thanSystem.Actionwhich is a Sub.