Use a property using its name in vb.net

For example:

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

So there is a question. Is it possible to access a property using its string name, for example Something ("car.chassis.wheel.radius") = 15?

+7
reflection
source share
2 answers

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

This function will receive 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 you error handling. And any consequences :)

+9
source share

Yes, you can very easily:

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

See this page for reference.

+2
source share

All Articles