Create and Populate an Object Via Reflection In C#
My latest project is a Json Serializer/Deserializer (Ferris.Json).
In working on Ferris.Json, I’m using reflection for the first time in my life.
I mainly work on business applications on my job. There aren’t many use cases where reflection is the appropriate tool for the job.
But for writing a json library, that definitely is the right tool.
Setting Types Up
First, let’s create a class to work with:
var testObj = new ReflectionObj
{
BoolProperty = true,
IntProperty = 1,
StringProperty = "hello",
};
A new object, with 3 properties.
Now we need to access it’s Type
.
Here are at least two ways to do that:
Type type = testObj.GetType();
Type anotherWay = typeof(ReflectionObj);
Activator.CreateInstance
Now that we have a Type
, we can leverage the Activator
to create a new instance of it:
object instance = Activator.CreateInstance(type);
CreateInstance
just returns an object
, so you’ll need to cast if you want the actual type:
ReflectionObj typedInstance = (ReflectionObj)Activator.CreateInstance(type);
You now have a type created via reflection
Populating Values
Now that we have a type, if we want to populate the values via reflection we can do something like this:
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (property.Name == "BoolProperty")
property.SetValue(instance, true);
else if (property.Name == "IntProperty")
property.SetValue(instance, 234);
else if (property.Name == "StringProperty")
property.SetValue(instance, "hello");
}
Obviously if you’re doing this at runtime, you can’t hard code property names.
But if you do some string manipulation, you can build a dictionary with name + value pairs.
//used string parsing to programmatically generate this Dictionary
var valueDict = new Dictionary<string, object>();
valueDict["BoolProperty"] = true;
valueDict["IntProperty"] = 234;
valueDict["StringProperty"] = "hello";
//Pull values and set them on your instance.
foreach (PropertyInfo property in properties)
{
if (valueDict.TryGetValue(property.Name, out var value))
{
property.SetValue(instance, value);
}
}
And there you have it. A simple way to programmatically populate an unknown object created through reflection.
The start of your own Json library.
Reflection Rabbit Hole
This also just scratches the surface on what you can do with reflection. It’s a powerful tool, but has its drawbacks.
So I personally would only use it if it’s the only tool for the job.