Skip to content

Instantly share code, notes, and snippets.

@wolf99
Last active May 5, 2017 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolf99/310b1ce7eec5e8a64c1de69872980c0b to your computer and use it in GitHub Desktop.
Save wolf99/310b1ce7eec5e8a64c1de69872980c0b to your computer and use it in GitHub Desktop.
VB.NET function to get a Dictionary of the names and values of the properties of a given object
Option Strict On
Option Explicit On
Imports System.Reflection
Module Gists
Public Function GetDictionaryOfProperties(ByRef o As Object) As Dictionary(Of String, Object)
Dim Properties As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
#If Not USE_LOOP
Properties = (From x In o.GetType().GetProperties()
Select x).ToDictionary(Of String, Object) _
(Function(x As PropertyInfo) (x.Name), ' Get string key from property name
Function(x As PropertyInfo) (x.GetGetMethod().Invoke(o, Nothing))) ' Get object value
#Else
' Equivalent loop version of the same thing
Dim PropertyInfos As PropertyInfo() = o.GetType().GetProperties() ' Get array of property infos
For Each x As PropertyInfo In PropertyInfos ' Step through each of the property infos
Dim PropertyName As String = x.Name ' Get string key from property name
Dim PropertyValue As Object = x.GetGetMethod().Invoke(o, Nothing) ' Get object value
Properties.Add(PropertyName, PropertyValue)
Next
#End If
Return Properties
End Function
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment