11

For example:

Sub Test()
  Dim car as new MyCar
  car.chassis.wheel.radius = 15
  Console.WriteLine(car.chassis.wheel.radius)    
End Sub

So question is. Is it possible to access the property using its string name like Something("car.chassis.wheel.radius") = 15?

Nikita Silverstruk
  • 1,067
  • 1
  • 20
  • 42
rqm.yorik
  • 111
  • 1
  • 1
  • 4

2 Answers2

17

You can, but not as concise as in your question.

This function will get any property of any object by name.

Public Function GetPropertyValue(ByVal obj As Object, ByVal PropName As String) As Object
    Dim objType As Type = obj.GetType()
    Dim pInfo As System.Reflection.PropertyInfo = objType.GetProperty(PropName)
    Dim PropValue As Object = pInfo.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)
    Return PropValue
End Function

I leave error handling to you. And any consequences :)

Miroslav Zadravec
  • 2,878
  • 4
  • 18
  • 31
4

Yes you can very easily:

Dim radius As Integer = CallByName(car.chassis.wheel, "radius", Microsoft.VisualBasic.CallType.Get, Nothing)

See this Microsoft page for reference.

pnizzle
  • 5,359
  • 3
  • 38
  • 70