I have a solution in VB.NET where I am implementing some custom attributes . One of them is for properties, eg:
Namespace Attributes
<AttributeUsage(AttributeTargets.Property)>
Public Class DescriptionAttribute : Inherits Attribute
Sub New(Name As String)
Me.Name = Name
End Sub
Public Property Name As String
End Class
End Namespace
I need to access the Name
of these attributes coming from the classes, so I've created an extension function for PropertyInfo
, like this:
<Extension()>
Function GetDescription(Prop As PropertyInfo) As String
Dim attr As DescriptionAttribute = Prop.GetCustomAttribute(GetType(DescriptionAttribute))
If (attr IsNot Nothing) Then Return attr.Name
Return Prop.Name
End Function
And I want to be able to use this function anywhere, such as Override
method ToString
:
Public Class Foo
<Description("Hello world with espace")>
Public Property HelloWorld As String
Public Overrides Function ToString() As String
return $"{HelloWorld.GetDescription()} - {HelloWorld}";
End Function
End Class
The problem is that I do not know how to access this attribute from the property. The only way I could get it would be if I did a search on an instance of the class, but I do not understand that is the best way to do it in VB.
How to solve?