0

I don't know which property of my object needs to be assigned until runtime.

The class instance is servicerecord and it has several properties defined as string:

public class ServiceRecord
 {
      public ServiceRecord(){}

       public string dos1 { get; set; }
       public string dos2 { get; set; }
       public string dos3 { get; set; }
       public string dos4 { get; set; }
       <snip>
  }

Let's say that at runtime, I discover that the program needs to assign a string value, say "11/2/2016" (i.e. the string representation of a date) to servicerecord.dos3.

How is that done using System.Reflection in C#?

In javascript it would be: servicerecord["dos3"] = ...

What's the C# counterpart to referring to a property by a string?

Tim
  • 8,669
  • 31
  • 105
  • 183

2 Answers2

1

You can use PropertyInfo to do this.

// Get property to write to.
PropertyInfo pi = _serviceRecord.GetType().GetProperty("dos3");
// Write value to property.
pi.SetValue(_serviceRecord, stringValue, null);
Derrick Moeller
  • 4,808
  • 2
  • 22
  • 48
0

Sounds to me like you'd want a Dictionary<string,string>. Remember to initialise your four entries in ServiceRecord's constructor

Alex F
  • 223
  • 2
  • 6