Let’s say we have the following class
class Client {
public string? Name { get; set; }
public int? Age { get; set; }
}
let’s create two instances from this class
Client client1 = new();
Client client2 = new();
let’s assign name for client1
and age for client2
client1.Name = "Omar";
client2.Age = 23;
Now if we look at memory, we can see that client1 have Age
as null and client2 have Name
as null.
We need to fill null values in client1
from client2
during runtime, sounds easy! right?
client1.Age = client2.Age;
sure that works, but let’s say our object have over 100 properties. Typing them one by one is boring as 🦆
So we are going to use reflection to parse them during runtime.
void CopyNullFields(object from, object to)
{
Type fromType = from.GetType();
Type toType = to.GetType();
if (fromType != toType)
return;
PropertyInfo[] fromProperties = fromType.GetProperties();
foreach (PropertyInfo property in fromProperties)
{
object? toValue = property.GetValue(to);
if (toValue == null) {
object? fromValue = property.GetValue(from);
property.SetValue(to, fromValue);
}
}
}
first we are getting type for both objects from
and to
if they are different we don’t need to do anything, it’s more like a checker
after making sure that both objects have same type, we get all properties of either of them, I chosen from
object
as we can see, we can access the properties of the object during runtime by using GetProperties
function
our object have properties Name
and Age
as shown in picture above
after having the properities, we loop over them, then we check if it’s null
we get the value from the to
object and we set it to from
object
CopyNullFields(from: client2, to: client1);
if we call this function by passing our clients, if take a look at memory we can see that now client1
get it’s age from client2
during runtime.
Final advice from kanna
You can download full code here source code