Created
April 5, 2011 06:46
-
-
Save jesperbjensen/903138 to your computer and use it in GitHub Desktop.
A nice extension method that maps properties from one type to another
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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