I have the following code I am trying to consolidate. (here are two examples) but with this repeated pattern of checking if fields are null then if they are different and if yes, then setting the new value into the old value.
What is the best way to rewrite this to avoid duplication?
if (String.IsNullOrEmpty(f.FirstName))
{
if (exisingPerson.FirstName != f.FirstName)
{
change = true;
exisingPerson.FirstName = f.FirstName;
}
}
if (String.IsNullOrEmpty(f.LastName))
{
if (exisingPerson.LastName != f.LastName)
{
change = true;
exisingPerson.LastName = f.LastName;
}
}
You can use delegates:
and call it with lambdas like this:
An even better thing to do would be to put the method in the
Personclass and eliminate that third parameter altogether, replacing it withthis.Probably overkill, but if you’re making a lot of these kind of property changes it might be valuable, and I think it’s an interesting pattern anyway.