Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save idusortus/23e7ae4a78ef89ac7f4aa520597ab777 to your computer and use it in GitHub Desktop.
Save idusortus/23e7ae4a78ef89ac7f4aa520597ab777 to your computer and use it in GitHub Desktop.
C# .Net Core 3.1 - Compare Two Objects, Replace Nulls

Example:

var cem = new TemplateEmailModel
{
    To = "idusortus@gmail.com",
    Subject = "SES Test"                              
};

var testCem = new TemplateEmailModel
{
    TemplateBody = "",
    Content = "Cottage cheese gouda croque monsieur. Cheese triangles cow chalk and cheese pepper jack goat squirty cheese cheese slices cow. Pepper jack swiss chalk and cheese cheese slices pecorino babybel cream cheese rubber cheese. Macaroni cheese everyone loves."
};

cem = MergeObjectsReplaceNulls(cem, testCem);

Stub method

// if customObject has null values, update with defaultObject values
public static T MergeObjectsReplaceNulls<T> (T customObject, T defaultObject)
{
    foreach (var property in typeof(T).GetProperties())
    {
        if (property.GetValue(customObject) == null)
        {
            property.SetValue(customObject, property.GetValue(defaultObject));
            Console.WriteLine($"Prop {property.Name} for object cem was NULL");
            Console.WriteLine($">> Set to {property.GetValue(defaultObject)}");
        }
        else
            Console.WriteLine($"property {property.Name} for object cem is NOT NULL");
    }
    return customObject;
}
Prop TemplateBody for object cem was NULL
>> Set to  Blah Blah Blah
property To for object cem is NOT NULL
property Subject for object cem is NOT NULL
property Content for object cem was NULL
>> Set to New Content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment