andrewb andrewb - 26 days ago 6
C# Question

Resolve string to a property of an object

I have a database table in SQL Server and I need to configure a .NET application to use some of the data in this table, this data is used in a SOAP API call.

For example, the table has these columns



FirstName | LastName | EmailAddress



The values in these columns need to map to certain fields in the API call. This configuration must be flexible, so I cannot just assign FirstName to apiobject.firstname, for example.

Is there a way to derive a string to a property of an object?

For example, for FirstName, would it be possible to resolve it to object.Firstname = value but not doing it like this

if(column == "FirstName")
{
ApiObject.FirstName = columnValue
}


Rather I would want to do something like

ApiObject.[somehow-resolve-which-field] = columnValue


Does anyone know what I am on about?

Answer

If you does not have notation of this class and you simply want to create an object with required properties - the right way is to use dynamic, as it noted in other answers.

If you already have a class, for example:

public class MyClass
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
}

You can do what you want with reflection as following:

var myObject = new MyClass();
var prop = myObject.GetType().GetProperty(column);
prop.SetValue(myObject, columnValue);

Where column and columnValue are from your example. Note that column should be of string type and columnValue should match the type of property.