Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an object to a Type extracted at runtime

I am using reflection to get an object's type, or for this issue an object that has instance properties type, at runtime and then I need to change an existing variable's type into that newly found type. Is this possible? For example, the following code does not work in the line indicated within:

Public Sub DoSomething(x As T, y As T, exp As String)

'This is a instance property on the object of a different type
'i.e. 'T.AnotherType' We need to reflect to find out what type of object
'AnotherType is and work with it
If exp.Split(".").Count Then
  Dim tp As Type = Nothing
  tp = x.GetType
  tp = tp.GetProperty(exp.Split(".").ElementAt(0)).PropertyType()
  'Line below works, gets the right type, and now I need both x and y values passed in to be cast to this type.
  Dim typ As Type = tp.GetType
  'The line below WILL NOT work; can't cast to an unknown type at compile time - makes sense, but this is where I need a solution
  x = DirectCast(x, typ)
End If

End Sub

I also tried CTypeDynamic avialable in .NET 4.0 and thought I was on to something. The line of code below actually compiles but at runtime gives the following error below.

x = CTypeDynamic(x, tp.GetType())

Conversion from type '[TypeOfT]' to type 'RuntimeType' is not valid.

Note above, [TypeOfT] is not actually in the error message but the type of object passed into the method.

So is there anyway without Case Statements or a bunch of 'If TypeOf(...' statements that I can use the type I found at runtime and convert another object to its type dynamically?

Thanks! (solution can be in VB.NET or C# - thank you)

like image 701
atconway Avatar asked Jan 25 '12 20:01

atconway


1 Answers

Try Convert.ChangeType

If exp.Split(".").Count Then
  Dim tp As Type = Nothing
  tp = x.GetType
  tp = tp.GetProperty(exp.Split(".").ElementAt(0)).PropertyType()
  'Line below works, gets the right type, and now I need both x and y values passed in to be cast to this type.
  Dim typ As Type = tp.GetType
  x = Convert.ChangeType(x, typ)
End If
like image 186
Chris Shain Avatar answered Nov 20 '22 07:11

Chris Shain