Thursday, May 14, 2015

A Partial Object Update Trick in C#

Intro

At least one time in my life someone has asked me a question that goes like this:

"I have a class with a bunch of properties. I want to update some or all of them, in any combination. How can I do this?"

Well you could just set the values of course, you could call a method that has an optional parameter for each property of the class, and you could of course pay a badger to write some clever new trick for you. We'll go with the badger option! The rest of the blog details what the badger would write.

Note: Sample code is in VS 2013.




Details

Within the class that you wish to update, create a SetAll or SetMany or whatever method where you pass in another instance of your class (source). Check each property and if it's non-null, you set the destination object's property value to the source object's property value. Note that this tactic will depend on nullable types, and assumes you can ignore null values passed into a new setter method. Here's an illustration:

using System;

namespace BlogPartialUpdateTrick
{
    public class SomeClass
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int? HeightInches { get; set; }
        public DateTime? Dob { get; set; }

        public void SetAll(SomeClass source)
        {
            this.FirstName = source.FirstName ?? this.FirstName;
            this.LastName = source.LastName ?? this.LastName;
            this.HeightInches = source.HeightInches ?? this.HeightInches;
            this.Dob = source.Dob ?? this.Dob;
        }

        public override string ToString()
        {
            return String.Format("fn: {0}, ln: {1}, height: {2}, DOB: {3}", FirstName ?? String.Empty, LastName ?? String.Empty, 
                HeightInches.HasValue ? HeightInches.Value.ToString() : "null", Dob.HasValue ? Dob.Value.ToShortDateString() : "null" );
        }
    }
}


In this first code sample, We have my spiffy class SomeClass. It's got 4 properties, all of which are nullable. The noteworthy part of this class is the SetAllMethod where I can pass in a source object which is also of type SomeClass. It sets this instance's property values to the values passed in the source parameter, but only if they're non-null. Here's a 2nd code blurb where I'm using this stuff:

using System;
using System.Windows.Forms;

namespace BlogPartialUpdateTrick
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var destination = new SomeClass() { FirstName = "Freddy", LastName = "Fingers", Dob = DateTime.Parse("01/01/1970"), HeightInches = 72 };
            var source = new SomeClass() { FirstName = null, LastName="Flippers", Dob = null, HeightInches = 80 };
            destination.SetAll(source);
            MessageBox.Show(destination.ToString());
        }
    }
}


Create a destination object, a source object, call the new method, voila! output is this:

"fn: Freddy, ln: Flippers, height: 80, DOB: 1/1/1970"

No comments:

Post a Comment