Reputation: 1419
In our codebase we have a lot of code like
if (Some.Property != someValue)
{
Some.Property = someValue;
}
Some.Property
:
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?
Upvotes: 2
Views: 296
Reputation: 1377
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);
Upvotes: 3