Suppose I have this simple class:
Public Class Person
Public Property Name() As String
Public Property Married() As Boolean
End Class
I want to create a delegate to its property getters. After a bit of search, including this, I've written this code in VB.NET:
Dim p As New Person()
p.Name = "Joe"
p.Married = True
Dim propGetter1 As Func(Of Boolean) = Function() p.Married
Dim propGetter2 As Func(Of String) = Function() p.Name
And retrieve the value of the properties as follows:
Dim married as Boolean = propGetter1.Invoke
Dim name as String = propGetter2.Invoke
It works fine, but contrary to the example in C# from the link above, it does not check at compile-time the type returned by the Function, so I could just write this code:
Dim propGetter1 As Func(Of Boolean) = Function() p.Name
Getting an error at runtime.
I've also tried this code:
Dim propGetter3 As Func(Of String) = Function(p As Person) p.Name
But I get the following error:
Nested function does not have a signature that is compatible with delegate 'System.Func(Of Boolean)'
So, how can I write this delegates with type-checking at compile-time, just like in C#??
EDIT:
As I've been asked to do so, I explain what I'm trying to do with this approach. I have an application that reads the state of a system (probe mesures, flows, preassures...) each few seconds, and stores this information in some properties of the objects that model the system.
I want to offer the user a list of all the objects defined which have properties that get their values updated this way. Therefore, the user can set alarm rules, so when a property reaches a certain value, an alarm is fired.
In orden to do so, I need to save delegates to the chosen properties, so I can check its values each few seconds, and compare them to the expected ones. Does it make sense?