Skip to content

Instantly share code, notes, and snippets.

@jesperbjensen
Created April 5, 2011 06:46
Show Gist options
  • Save jesperbjensen/903138 to your computer and use it in GitHub Desktop.
Save jesperbjensen/903138 to your computer and use it in GitHub Desktop.
A nice extension method that maps properties from one type to another
<Extension()> _
Public Sub FillWith(ByVal destination As Object, ByVal source As Object, ByVal ParamArray ignoredProps() As String)
Dim sourceType = source.GetType()
Dim props As New Dictionary(Of String, String)
For Each prop As String In ignoredProps
props.Add(prop, prop)
Next
For Each objProperty In destination.GetType().GetProperties()
Dim sourceProperty = sourceType.GetProperty(objProperty.Name)
If sourceProperty IsNot Nothing AndAlso Not props.ContainsKey(sourceProperty.Name) AndAlso objProperty.CanWrite Then
Dim value = sourceType.GetProperty(objProperty.Name).GetValue(source, Nothing)
If value Is Nothing Then
Continue For
End If
If value.GetType() Is objProperty.PropertyType Then
objProperty.SetValue(destination, value, Nothing)
End If
End If
Next
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment