Click here to Skip to main content
15,891,423 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Finding Properties in Objects and Write and Read to them

Rate me:
Please Sign up or sign in to vote.
4.83/5 (3 votes)
20 Nov 2014CPOL 13K   107   2   1
Sometimes, it is useful to know if an object has a certain property and then fill it by only having the propertyname as a string at hand.

Introduction

Sometimes, it is useful to know if an object has a certain property and then fill it by only having the propertyname as a string at hand.

Background

The core can be found in 2 functions. They are a bit FAT but I copied them from a project I made where I first generate VB.NET code for an Class entity using the data returned from a .NET DataTable object. Next, this entity can bind itself as long as the fieldnames don't change in the database.

I included a sample project where we were experimenting a bit with this. You are welcome to use it.

The Code

The 2 functions are given below:

VB.NET
GET_SET_PropertyValue(name as string , optional Value as object)

findproperty(ByVal name As String, ByRef myProps As PropertyInfo) As String

Function 2 iterates through all properties and looks for the one you need. Function one sets and gets a property by only querying the string you enter at first. If it does not find the property, it uses Findproperty to look a bit deeper.

VB.NET
''' <summary>
'''Find, Set and Get properties
''' </summary>
''' <param name="name">The name of property.</param>
''' <param name="value">optional The value if you want to set .</param>
''' <returns></returns>
Private Function GET_SET_PropertyValue_
(name As String, Optional value As Object = Nothing) As List(Of Object)
    Dim OriginalName As String = ""
    Dim propertyType As System.Type = Nothing
    Dim myProps As System.Reflection.PropertyInfo = Nothing
    Dim PropValue As Object = Nothing
    Dim returnlist As New List(Of Object)
    '' type of the setter object
    Dim SetterValueType As System.Type = Nothing

    Try

        'try to find the property
        myProps = Me.GetType.GetProperty(name)
        '' is the infoObject is not empty we found it
        If Not (myProps Is Nothing) Then
            ''set the original name of the property
            OriginalName = name
        Else
            ' Lets see if we find it in all the collection of properties
            ' using findproperty(ByVal name As String, ByRef myProps As PropertyInfo)
            ' returning the name if its there.
            OriginalName = findproperty(name, myProps)
        End If

        If myProps Is Nothing Or OriginalName = "" Then
            'we found nothing :(
            returnlist.Add("error")
            returnlist.Add(name)
            returnlist.Add(name & " as a property name was not found.")
            returnlist.Add(name.GetType)
            Return returnlist ' ================> exit
        End If

    Catch ex As Exception
        If returnlist.Count > 0 Then returnlist = New List(Of Object)
        returnlist.Add("error")
        returnlist.Add(name)
        returnlist.Add(ex.Message)
        returnlist.Add(Err.GetType.ToString)
        Return returnlist ' ================> exit
    End Try


    '' GETTING PROPERTY VALUE
    If (value Is Nothing) Then '
        Try  'ALMOST HOME set the type  'no value to set so we want to get a value
            propertyType = myProps.GetType
            PropValue = myProps.GetValue(Me, Nothing)
            returnlist.Add("success")
            returnlist.Add(OriginalName)
            returnlist.Add(PropValue)
            returnlist.Add(propertyType.GetType.ToString)
            '' YEEEEEEEE FOUND IT
            Return returnlist ' ================> happy exit
        Catch ex As Exception
            If returnlist.Count > 0 Then returnlist = New List(Of Object)
            returnlist.Add("error")
            returnlist.Add(name)
            returnlist.Add(ex.Message)
            returnlist.Add(Err.GetType.ToString)
            Return returnlist ' ================> exit
        End Try
    End If

    '' SETTING PROPERTY VALUE
    Try  'ALMOST HOME WE READY TO SET A NEW VALUE
        'we change the property value
        propertyType = myProps.GetType
        SetterValueType = value.GetType
        myProps.SetValue(Me, value)

        returnlist.Add("success")
        returnlist.Add(OriginalName)
        returnlist.Add("your object type: " & SetterValueType.GetType.ToString)
        returnlist.Add("the property type:" & propertyType.GetType.ToString)

        Return returnlist ' ================> happy exit

    Catch ex As Exception
        returnlist.Add("error")
        returnlist.Add(OriginalName)
        returnlist.Add(name)
        returnlist.Add(ex.Message)
        returnlist.Add(Err.GetType.ToString)
        returnlist.Add("your object type: " & SetterValueType.GetType.ToString)
        returnlist.Add("the property type:" & propertyType.GetType.ToString)
        Return returnlist ' ================>unhappy  happy exit
    End Try

End Function

''' <summary>
''' Findproperties the specified name by iterating through  all the properties
''' See function getAllProperties() As String() it uses this method to return a string() array
''' and by reference ByRef myProps As PropertyInfo.
''' </summary>
''' <param name="name">The name.</param>
''' <param name="myProps">My props.</param>
''' <returns>The propertyName as a string and _
''' ByRef the myProps As PropertyInfo object </returns>
'''
Private Function findproperty(ByVal name As String, ByRef myProps As PropertyInfo) As String
    Dim myMembers As PropertyInfo() = Me.GetType.GetProperties()
    Dim propertyname As String = ""

    Try
        If myMembers.Length > 0 Then
            Dim index As Integer
            For index = 0 To myMembers.Length - 1
                ''  System.Diagnostics.Debug.Print((LCase(name))
                ''  & "=" & LCase(myMembers(index).Name))

                If LCase(myMembers(index).Name) = (LCase(name)) Then
                    myProps = myMembers(index)
                    propertyname = myMembers(index).Name
                    Return propertyname
                End If
            Next index

            myProps = Nothing
            Return propertyname
        Else
            myProps = Nothing
            Return propertyname
        End If

    Catch ex As Exception
        myProps = Nothing
        Return propertyname
    End Try
End Function

Getting the Properties from an Object

It is useful to use this one first and then set or read the properties with the code above.

VB.NET
''' <summary>
''' you can throw in any class and pray for the best See the overloaded method (of T))
''' </summary>
''' <typeparam name="T">the system type of the class</typeparam>
''' <param name="foreigner">The foreigner: instance of that class</param>
''' <returns>a array of  String()</returns>
'''
Public Function getAllProperties(Of T)(foreigner As T) As String()
    Dim pString As String()
    Try

        Dim myMembers As PropertyInfo() = foreigner.GetType.GetProperties()

        If myMembers.Length > 0 Then
            pString = New String(myMembers.Length - 1) {}

            Dim index As Integer

            For index = 0 To myMembers.Length - 1
                pString(index) = myMembers(index).Name
            Next index

            Return pString
        Else
            pString = New String(0) {}
            pString(0) = "noproperties|system.Error"
        End If

    Catch ex As Exception
        pString = New String(0) {}
        pString(0) = "ERROR|" & ex.Message
    End Try

    Return pString

End Function

History

  • 20th November, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
Hong Kong Hong Kong
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
_Vitor Garcia_21-Nov-14 3:37
_Vitor Garcia_21-Nov-14 3:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.