1

For some time I have been wondering if it is possible to enumerate, or set and index for the properties of an object or structure.

I currently have a set of custom graph generator classes for different reports, but they all accept the same structure as a parameter.

The structures' properties' values get set from a SQL reader that reads columns as they are set up in a table in the database. Now ideally want to loop though these column values sequentially and write them to the properties of the structure.

My Structure is as follows:

Public Structure MyStructure
    Dim GraphName As String
    Dim GraphValue As Integer
    Dim Red As Integer
    Dim Green As Integer
    Dim Blue As Integer
End Structure

Now I want to be able to loop through these properties and assign values to each. E.g.:

 Dim Struct as MyStructure
 For i as integer = 0 to 4
      Struct.i = "A value retrieved from database"
 Next i

The main idea is that i want to avoid using a case statement:

 Dim Struct as MyStruct
 For i as integer = 0 to 4
      Select Case i
          Case 0
          Struct.GraphName  = "A value retrieved from database"
          Case 1
          Struct.GraphValue = "A value retrieved from database"
          'Etc.
      End Select
 Next i

Any insight on this will be much appreciated.

Eugene de Lange
  • 93
  • 2
  • 12
  • see here: http://stackoverflow.com/questions/997747/c-sharp-reflection-accessing-the-fields-of-a-struct – igrimpe Dec 12 '12 at 08:32
  • also: [Map a dataset to a custom .NET object](http://stackoverflow.com/questions/10618360/map-a-dataset-to-a-custom-net-object-in-asp-net) – sloth Dec 12 '12 at 08:47

1 Answers1

0

To "dynamically" access the fields, you would use reflection:

Private Structure foo
    Public i As Integer
    Public s As String
End Structure

Private Sub bar()

    Dim f As foo
    Dim fields = GetType(foo).GetFields(BindingFlags.Public Or BindingFlags.Instance)
    For Each fi As FieldInfo In fields
        fi.SetValue(f, GetValueFromDBForName(fi.Name))
    Next

End Sub

Be aware that Reflection is NOT fast. "FasterFlect" (via NuGet) or other "fast" replacements might be an alternative. OR you consider to use an ORM (object relational mapping) "out-of-the-box"

igrimpe
  • 1,775
  • 11
  • 12