How to check if the property has description attribute?

Hobbyist_programmer 621 Reputation points
2021-02-22T20:32:35.677+00:00

Hallo

I have an object like below and i want to get or check only the property which has description attribute. I can loop through like below but dont know how to check for the property with description attribute.

Public Class Sample

Public Property ID as integer
<Description("Descr1")>Public Property Val1 as integer
<Description("Descr1")>Public Property Val2 as integer

End Class

For Each prop In obj.GetType().GetProperties
   '//print only property with description attributes
Next

Thanks

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,579 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2021-02-22T21:47:18.963+00:00

    If the value of the <Description(…)> attribute does not matter, then try this code:

    Dim selected_properties As List(Of PropertyInfo)
    
    selected_properties =
       GetType(Sample) _
          .GetProperties() _
          .Where(Function(p) p.GetCustomAttributes().Any(Function(a) TypeOf a Is DescriptionAttribute)) _
          .ToList
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Dewayne Basnett 1,116 Reputation points
    2021-02-23T16:57:36.56+00:00

    I'd use LINQ but it is up to you

    Imports System.ComponentModel
    Imports System.Reflection
    
    Public Class Form1
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            Dim selProp As IEnumerable(Of PropertyInfo)
    
            selProp = From p In GetType(Sample).GetProperties()
                         From a In p.GetCustomAttributes
                         Where TypeOf a Is DescriptionAttribute
                         Select p
    
           'OR
    
            For Each p As PropertyInfo In GetType(Sample).GetProperties()
                For Each a As Attribute In p.GetCustomAttributes
                    If TypeOf a Is DescriptionAttribute Then
    
                    End If
                Next
            Next
        End Sub
    End Class
    
    Public Class Sample
        <Description("Name")> Public Property Name As String = "name"
        Public Property ID As Integer
        <Description("Descr1")> Public Property Val1 As Integer
        <Description("Descr2")> Public Property Val2 As Integer
        <Obsolete("Descr3", False)> Public Property Val3 As String = "FOO"
    End Class
    
    0 comments No comments