Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Getting a property using reflection part 2
From Wiki
So the first part was simple.
And I want to keep it simple for just a while.
I want to make the reflection part a bit easier for myself and for others.
So I made a Class with shared methods (one for now).
- Namespace Common
- ''' <summary>
- '''
- ''' </summary>
- ''' <typeparam name="T"></typeparam>
- ''' <typeparam name="K"></typeparam>
- ''' <remarks></remarks>
- Public Class GetPropertyByReflection(Of T, K)
- #Region " Public methods "
- ''' <summary>
- '''
- ''' </summary>
- ''' <param name="PropertyName"></param>
- ''' <param name="ObjectToReflect"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- Public Shared Function GetProperty(ByVal PropertyName As String, ByVal ObjectToReflect As K) As T
- Dim _Object As Object = ObjectToReflect
- Return CType(_Object.GetType.GetProperty(PropertyName , Reflection.BindingFlags.Instance Or Reflection.BindingFlags.IgnoreCase Or Reflection.BindingFlags.Public).GetValue(ObjectToReflect, Nothing), T)
- End Function
- #End Region
- #Region " Private methods "
- #End Region
- End Class
- End Namespace
As you can see, I use reflection so the users of this Class don't have to cast and so it is type safe.
This will make the test look a bit like this:
- ''' <summary>
- '''
- ''' </summary>
- ''' <remarks></remarks>
- <Test()> _
- Public Sub TestReflectionGetValueForRemarks()
- Dim _Translated As Common.Interfaces.ITranslated
- _Translated = New Common.Translated
- _Translated.Remarks = "Test"
- Assert.AreEqual("Test", Common.GetPropertyByReflection(Of String, Model.KitManagement.Interfaces.ICondition).GetProperty("Remarks", _Translated))
- End Sub
One line and typesafe, what more do you want? I know the K wasn't really necessary but it makes sure it gets the correct object.
Run it, and green again. Life can be so beautiful.



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.