VARIABLE CLASS MEMBER ASSIGNMENT

Mark Devid

Total Post:102

Points:714
Posted by  Mark Devid
VB.Net 
 899  View(s)
Ratings:
Rate this:
Hi Developers, 

How to use a variable string for member assignment of a class. The field to be compared is represented by an integer value, and based off of an enumeration I want to compare the field represented by that integer. For example, here is the basic idea of what I am trying to accomplish.

My line of code as following

Public Class Point
   Public X As Double
   Public Y As Double
   Public Z As Double
End Class

Public Enum PointEnum As Short
   X = 0
   Y = 1
   Z = 2
End Enum

With a list of Points, I want to be able to compare x, y, or z depending on 'enumValue' that is passed into the program.

Dim PointList As New List(Of Point)
If PointList(0).[Enum].GetName(GetType(PointEnum), enumValue) < someValue Then
   ...
End If

The PointList(0).[Enum].GetName(GetType(PointEnum), enumValue) is the line I am having trouble with.. If my actual code were as simple as having x, y, and z I would just use a select case or if statements, however the class I am using has over 30 properties. 

Any help appreciated.
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Variable class member assignment

    Hi Mark,


    If all the fields in the classes are PUBLIC as shown, then you can use the legacy CallByName() function, which makes it really easy to write/read:

        Dim PointList As New List(Of Point)
        PointList.Add(New Point() With {.X = 1.0, .Y = 2.0, .Z = 3.0})
        PointList.Add(New Point() With {.X = 3.0, .Y = 6.0, .Z = 9.0})
        PointList.Add(New Point() With {.X = 4.0, .Y = 8.0, .Z = 12.0})

        Dim enumValue As PointEnum = PointEnum.Z
        Dim someValue As Double = 5

        If CallByName(PointList(0), enumValue.ToString, CallType.Get) < someValue Then
            Debug.Print("Less Than")
        Else
            Debug.Print("Not Less Than")
        End If

    If you'd really like to use Reflection, or if the fields are not Public, then I have a similar example here.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!