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


/ Published in: Visual Basic
Save to your folder(s)

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:

pants.CopyPropertiesTo(shirt)


Copy this code and paste it in your HTML
  1. <System.Runtime.CompilerServices.Extension()> _
  2. Public Sub CopyPropertiesTo(ByVal src As Object, ByVal dest As Object)
  3. If dest Is Nothing Then
  4. Exit Sub
  5. End If
  6. Dim srcType As Type = src.GetType()
  7. Dim destType As Type = dest.GetType()
  8. Dim pi() As PropertyInfo = srcType.GetProperties(BindingFlags.Public Or BindingFlags.GetProperty Or BindingFlags.Instance)
  9. For Each p1 As PropertyInfo In pi
  10. Dim p2 As PropertyInfo = destType.GetProperty(p1.Name, BindingFlags.Public Or BindingFlags.SetField Or BindingFlags.Instance)
  11. If p2 IsNot Nothing Then
  12. If p2.PropertyType Is p1.PropertyType Then
  13. p2.SetValue(dest, p1.GetValue(src, Nothing), Nothing, Nothing, Nothing, Nothing)
  14. End If
  15. End If
  16. Next
  17. End Sub

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.