Copy Null Values From Another Object Using Reflection

Aug 26, 2023  │  m. Oct 14, 2023 by Omar ElKhatib  │  #dotnet   #csharp   #reflection  
Disclaimer: Views expressed in this software engineering blog are personal and do not represent my employer. Readers are encouraged to verify information independently.

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.

image 1

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

Kanna Kamui

In real world setup it's good practice to let the caller know that passed objects have different types

after making sure that both objects have same type, we get all properties of either of them, I chosen from object

image 2

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.

image 3

Final advice from kanna

Kanna Kamui

There is drawback for using reflection, reflection is slow so consider it in case of where performance is critical. Other than that we can easly shoot our self in the foot, because we don't have type safety.

You can download full code here source code