Simple Generic Upcast example in vb.net using reflection

Here is a quick example of how one can use reflection to perform an upcast in vb.net. 

In the sample code below, you have  a person class and a contact class.  The contact class inherits from the person class.  Additionally, you have an instance of the Person class which needs to be converted to an instance of the Contact class.  The below code can be used to perform this conversion. 

This may not be the best way to do this, but it is certainly an easy and quick way of performing the task.

  1. Module Module1
  2.  
  3.     Sub Main()
  4.         Dim p As New Person() With {.First = "Test", .Last = "User"}
  5.         Console.WriteLine("{0} {1} {2}", p.GetType.FullName, p.First, p.Last)
  6.  
  7.         Dim c As Contact = Upcast(Of Person, Contact)(p)
  8.         c.Phone = "555-123-4567"
  9.         Console.WriteLine("{0} {1} {2} {3}", c.GetType.FullName, c.First, c.Last, c.Phone)
  10.         c.CallContact()
  11.  
  12.         Console.ReadLine()
  13.     End Sub
  14.  
  15.     Public Function Upcast(Of B, S As {New, B})(ByVal baseObj As B) As S
  16.         Dim superObj As S = New S()
  17.         Dim superProp As System.Reflection.PropertyInfo = Nothing
  18.  
  19.         For Each baseProp As System.Reflection.PropertyInfo In baseObj.GetType().GetProperties()
  20.             superProp = superObj.GetType().GetProperty(baseProp.Name)
  21.             superProp.SetValue(superObj, baseProp.GetValue(baseObj, Nothing), Nothing)
  22.         Next
  23.  
  24.         Return superObj
  25.     End Function
  26.  
  27.     Public Class Person
  28.         Private _First As String
  29.         Private _Last As String
  30.  
  31.         Public Property First() As String
  32.             Get
  33.                 Return _First
  34.             End Get
  35.             Set(ByVal value As String)
  36.                 _First = value
  37.             End Set
  38.         End Property
  39.  
  40.         Public Property Last() As String
  41.             Get
  42.                 Return _Last
  43.             End Get
  44.             Set(ByVal value As String)
  45.                 _Last = value
  46.             End Set
  47.         End Property
  48.     End Class
  49.  
  50.     Public Class Contact
  51.         Inherits Person
  52.  
  53.         Private _Phone As String
  54.         Public Property Phone() As String
  55.             Get
  56.                 Return _Phone
  57.             End Get
  58.             Set(ByVal value As String)
  59.                 _Phone = value
  60.             End Set
  61.         End Property
  62.  
  63.         Public Sub CallContact()
  64.             Console.WriteLine("Calling {0}....", Phone)
  65.         End Sub
  66.     End Class
  67. End Module