Question

I have a set of methods that allows users to easily user the PropertHasChanged event and allows then to do some extra processing. Here is the method:

public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action<T> extraFunction = null, Action voidAfterSetAction = null) where T : class
        {
            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(newValue);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }

It has become apparent to me that I would sometimes need the old value in the extraFunction action. This is how I intended to do that:

public virtual void SetPropertyValue<T>(ref T currentValue, T newValue, Action<T, T> extraFunction = null, Action voidAfterSetAction = null) where T : class
        {
            var oldVal = currentValue;

            if (currentValue == newValue) return;

            currentValue = newValue;

            PropertyHasChanged();

            if (extraFunction != null) extraFunction(oldVal, newValue);

            if (voidAfterSetAction != null) voidAfterSetAction();
        }

As you may notice, the extraFunction action now takes two parameters. VS didnt have an issue with me creating the method (no red qwigglies) but when I build it throws MANY errors that say that the usage between the first method and the second method is ambiguous. If that is the case then how can I achieve what I am looking for?

EDIT

Here is the usual usage of the method:

SetPropertyValue(ref _streetAddress1, value, null, () => SalesData.StreetAddress1 = value);
Was it helpful?

Solution

Firstly, this is not overriding - this is overloading.

It's fine from the point of view of the method declarations - I suspect it's the call sites which are ambiguous. Unfortunately you haven't shown us any of those.

Personally I would use two different names here to keep things simpler. Overloading can be a complex business, and by the time you've got delegates involved (with anonymous functions, method group conversions etc) it's even worse than normal - and optional parameters add to the complexity too! Having methods with different names keeps things much clearer.

Alternatively, do you need to overload it at all? Can't you just have the version with the Action<T, T> and just ignore the "old" value within the callback when you don't care about it? That would simplify things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top