2

In our codebase we have a lot of code like

if (Some.Property != someValue)
{
    Some.Property = someValue;
}

Some.Property:

  1. comes from third party libraries and cant be changed
  2. has expensive setter

I want to refactor this to be more clear. In C++ i'd be able to write a macros UpdateIfChanged.

Is there way to do this besides writing extensions for Some class, e.g. with generics?

kilotaras
  • 1,419
  • 9
  • 24
  • Are you talking about Databinding? – DotNetRussell Mar 28 '14 at 13:12
  • No, its actually AddIn for office. – kilotaras Mar 28 '14 at 13:15
  • 1
    I see two options, either you make a bunch of extension methods, perhaps one which takes a lamdba pointing to the property you want to change. Then you can have one generic extension. The other option is to use the decorator pattern, then you can hide the third party class inside your own interface or whatever. In there you can hide all these checks. – Zache Mar 28 '14 at 13:35

1 Answers1

3

Why not use a generic method for your needs. Which does that code on its own?

Something like:

    public static void SetIfChanged<T>(ref T prop, T value)
    {
        if (object.Equals(prop, value) == false)
        {
            prop = value;
        }
    }

And then use it like:

SetIfChanged(ref someProp, someValue);

EDIT v2 Your comment is correct. That does not work with properties.

This solution is not that pretty but works:

    public static void SetIfChanged<T>(T value, T newValue, Action<T> action)
    {
        if (object.Equals(value, newValue) == false)
        {
            action(value);
        }
    }

Usage:

SetIfChanged(t.ASDF, newVal, X => t.ASDF = newVal);
toATwork
  • 1,335
  • 16
  • 34
  • That what i tried first. someProp has to be variable for this to work. – kilotaras Mar 28 '14 at 13:28
  • object.Equals(value, newValue) will be false as you'd try to compare Action and T – kilotaras Mar 28 '14 at 13:44
  • @kilotaras you got me again. I did fix it. But to be honest, I'd stick with the if statement - when I look at that code. – toATwork Mar 28 '14 at 13:54
  • i'm going to do that as well. I was hoping for something as elegant as C++ `#define UPDATE(a,b) if (a!=b){a=b;}` – kilotaras Mar 28 '14 at 13:56
  • @kilotaras out of interest: about how many properties are we talking? Maybe an extension method might be the more elegant way! – toATwork Mar 28 '14 at 13:57
  • about 7-8, but each of them is used in such a way no more than twice, so extension methods may be overkill. – kilotaras Mar 28 '14 at 14:04