0

I have a VB class. It's big, so I'm posting a simplified example here:

Public Class ExampleClass
    Public Property Foo As String
    Public Property Bar As String
End Class

Suppose I have a text file like this:

foo,123
bar,456

And I want to read the file and populate the properties of my object accordingly.

Simplest way I can think of is to add a method with a case statement, like this:

Public Class ExampleClass
    Public Property Foo As String
    Public Property Bar As String
    Public Sub SetProperty(prop As String, val As String)
        Select Case prop
            Case "Foo"
                Foo = val
            Case "Bar"
                Bar = val
        End Select
    End Sub
End Class

But as my class will have around a hundred properties, so my SetProperty procedure is going to get big and boring to put together, and probably not be the most maintainable. Is there a better way to do this?

Before you tell me, I shouldn't structure my data this way, I know. However, this is a legacy database table that I have to live with. I'm updating the application with some new Entity Framework and LINQ code that will allow me to drop some very ugly stored procedures.

Thanks for your help.

James

James Shields
  • 309
  • 4
  • 12
  • Are you a co-worker of this question's OP? http://stackoverflow.com/questions/29822402/populate-a-structure#comment47775946_29822402 As mentioned there in the comments you could have a look at [CSV Helper](http://joshclose.github.io/CsvHelper/) which has auto mapping features. It either initializes the properties in the order they appear in the file or from a mapping-file. That might work for you. – Tim Schmelter Apr 23 '15 at 14:37
  • You can use reflection to set property value. – SelvaS Apr 23 '15 at 14:38
  • 2
    Use reflection, example here: http://stackoverflow.com/questions/12970353/c-sharp-dynamically-set-property – Rick S Apr 23 '15 at 14:41

1 Answers1

1

You can find each object property via reflection

    MyClass myClass = new MyClass();

    System.Reflection.PropertyInfo pi = myClass.GetType().GetProperty("Foo");

        if (pi  != null && pi.CanWrite)
        {
           //Check the type before assignment...
           if (pi.PropertyType.IsAssignableFrom(typeof(string)))
               pi.SetValue(myClass, value, null);
        }