How to force the occurrence of an event from an extension method?

1

I'm creating an application in C # and I'm using the INotifyPropertyChanged interface like this:

public class Test: INotifyPropertyChanged
{
    private int foo;
    public int Foo { get => foo; set => Set(ref foo, value); }

    public void Set<T>(ref T property, T value, [CallerMemberName]string p = "")
    {
        property = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p));
    }

}
My problem is that whenever I want to implement this form of work (with the Set(ref property, value) method I am required to come here and copy the code and reimplement it. From this problem, I thought of a method of extension like this:

using System.Runtime.CompilerServices;

public static class Extensions 
{
    public static void Set<T>(
        this INotifyPropertyChanged source, ref T property, T value,
        [CallerMemberName]string propertyName = "")
    {
        property = value;
        source.PropertyChanged?
            .Invoke(source, new PropertyChangedEventArgs(propertyName));
    }
}

My problem is that if I try to do this implementation, I get this message:

  

The event INotifyPropertyChanged.PropertyChanged can only appear on the left hand side of + = or - =

What do I need to do to force the call of this event through an extension property?

    
asked by anonymous 04.12.2018 / 16:26

1 answer

1

I do not have the slightest idea of what you want to do, because it does not have the complete implementation, it seems something very wrong, but to strictly solve your problem you have to pass the event handler as a parameter to the method you want and explicitly call . In fact I saw no advantage in having this as an extension method.

I had to by some other things to satisfy the interface:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class Program {
    public static void Main() {
        var x = new Test();
        x.Foo = 10;
    }
}
public class Test: INotifyPropertyChanged {
    private int foo;
    public int Foo { get => foo; set => this.Set(ref foo, value, PropertyChanged); }
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(name));
    }
}

public static class Extensions {
    public static void Set<T>(
        this INotifyPropertyChanged source, ref T property, T value, PropertyChangedEventHandler handler, [CallerMemberName]string propertyName = "") {
        property = value;
        handler?.Invoke(source, new PropertyChangedEventArgs(propertyName));
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

    
04.12.2018 / 17:10