Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in C# to access an object's fields using field names generated at runtime

Here is what I mean:

I need to be able to substitute this ugly looking C# code:

if (attribute.Name == "Name") machinePool.Name = attribute.Value;
else if (attribute.Name == "Capabilities") machinePool.Capabilities = attribute.Value;
else if (attribute.Name == "FillFactor") machinePool.FillFactor = attribute.Value;

into something like this:

machinePool.ConvertStringToObjectField(attribute.Name) = attribute.Value;

There is no ConvertStringToObjectField() method, but I would like to have something like this, if it's possible. I have access to the machinePool object class code, so I can add neccessary code, but I am not sure what code it may be or is it even possible to do in C#.

like image 303
LikeToCode Avatar asked Jan 24 '23 01:01

LikeToCode


1 Answers

Yes, you can do this through reflection:

var fieldInfo = machinePool.GetType().GetField(attribute.Name);
fieldInfo.SetValue(machinePool, attribute.Value);

You could also create an extension method to make things easier:

public static void SetField(this object o, string fieldName, object value)
{
    var fi = o.GetType().GetField(fieldName);
    fi.SetValue(o, value);
}
like image 96
Lee Avatar answered Jan 25 '23 16:01

Lee