Return to Snippet

Revision: 27809
at June 24, 2010 05:12 by s0lidmetal

Initial Code
<System.Runtime.CompilerServices.Extension()> _
        Public Sub CopyPropertiesTo(ByVal src As Object, ByVal dest As Object)
            If dest Is Nothing Then
                Exit Sub
            End If
            Dim srcType As Type = src.GetType()
            Dim destType As Type = dest.GetType()
            Dim pi() As PropertyInfo = srcType.GetProperties(BindingFlags.Public Or BindingFlags.GetProperty Or BindingFlags.Instance)
            For Each p1 As PropertyInfo In pi
                Dim p2 As PropertyInfo = destType.GetProperty(p1.Name, BindingFlags.Public Or BindingFlags.SetField Or BindingFlags.Instance)
                If p2 IsNot Nothing Then
                    If p2.PropertyType Is p1.PropertyType Then
                        p2.SetValue(dest, p1.GetValue(src, Nothing), Nothing, Nothing, Nothing, Nothing)
                    End If
                End If
        End Sub

Initial URL

Initial Description
This copies all property values from Class A to Class B. Useful if you have many unrelated classes that share similar properties and you are constantly writing code like:

    shirt.Color = pants.Color
    shirt.Pattern = pants.Pattern
    shirt.Style = pants.Style

Could change to:


Initial Title
Reflection extension method to copy properties from one object to another object.

Initial Tags

Initial Language
Visual Basic