Tim Tim - 1 month ago 6
C# Question

How to assign a value to one of an object's properties if the property name is not known until runtime

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?

Answer

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);
Comments