'How can I pass a property as a parameter without passing the property name as a string in VB.NET?
I want to access a property inside another method without passing the property name as a string. There are two reasons for this requirement:
- I cannot pass the property value, as I may not want to evaluate it, but retrieve it from a cache instead (the cache will be more efficient in my setup, for some properties).
- I do not want to pass the name as a string because compile-time errors will not be raised if the string is invalid.
After hours of searching, I have not found a definite answer (which makes me wonder if one exists!). I have explored the following options so far:
- Using ByRef - This does not give the ability to access the property name.
- Using Reflection - This would need to have the property name passed in as a string, which I want to avoid (from Alois at GeeksWithBlogs (via the Internet Archive)).
- Using Delegation - This looked like the most likely method, but properties are not supported (from a thread at Extreme.NetTalk).
Below is an oversimplified demonstration of how I would implement this if properties could be used in delegation:
Delegate Property FunctionName() As String
Public Function GetPropName(ByVal prop As FunctionName) As String
Return prop.Method.Name
End Function
Public Sub Test()
Dim x As New MyType()
' This should print 'Definition'
Debug.Print(GetPropName(AddressOf x.Definition))
End Sub
Is there a way to pass a property as a parameter - in a format which allows access to both its name and value - without passing the property name as a string?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
