Why sending events to a sender is not allowed in C #?

advertisements

Quote from: http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

"Invoking an event can only be done from within the class that declared the event."

I am puzzled why there is such restriction. Without this limitation I would be able to write a class (one class) which once for good manages sending the events for a given category -- like INotifyPropertyChanged.

With this limitation I have to copy and paste the same (the same!) code all over again. I know that designers of C# don't value code reuse too much (*), but gee... copy&paste. How productive is that?

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

In every class changing something, to the end of your life. Scary!

So, while I am reverting my extra sending class (I am too gullible) to old, "good" copy&paste way, can you see

what terrible could happen with the ability to send events for a sender?

If you know any tricks how to avoid this limitation -- don't hesitate to answer as well!

(*) with multi inheritance I could write universal sender once for good in even clearer manner, but C# does not have multi inheritance

Edits

The best workaround so far

Introducing interface

public interface INotifierPropertyChanged : INotifyPropertyChanged
{
    void OnPropertyChanged(string property_name);
}

adding new extension method Raise for PropertyChangedEventHandler. Then adding mediator class for this new interface instead of basic INotifyPropertyChanged.

So far it is minimal code that let's send you message from nested object in behalf of its owner (when owner required such logic).

THANK YOU ALL FOR THE HELP AND IDEAS.

Edit 1

Guffa wrote:

"You couldn't cause something to happen by triggering an event from the outside,"

It is interesting point, because... I can. It is exactly why I am asking. Take a look.

Let's say you have class string. Not interesting, right? But let's pack it with Invoker class, which send events every time it changed.

Now:

class MyClass : INotifyPropertyChanged
{
    public SuperString text { get; set; }
}

Now, when text is changed MyClass is changed. So when I am inside text I know, that if only I have owner, it is changed as well. So I could send event on its behalf. And it would be semantically 100% correct.

Remark: my class is just a bit smarter -- owner sets if it would like to have such logic.

Edit 2

Idea with passing the event handler -- "2" won't be displayed.

public class Mediator
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string property_name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property_name));
    }

    public void Link(PropertyChangedEventHandler send_through)
    {
        PropertyChanged += new PropertyChangedEventHandler((obj, args) => {
            if (send_through != null)
                send_through(obj, args);
        });
    }

    public void Trigger()
    {
        OnPropertyChanged("hello world");
    }
}
public class Sender
{
    public event PropertyChangedEventHandler PropertyChanged;

    public Sender(Mediator mediator)
    {
        PropertyChanged += Listener1;
        mediator.Link(PropertyChanged);
        PropertyChanged += Listener2;

    }
    public void Listener1(object obj, PropertyChangedEventArgs args)
    {
        Console.WriteLine("1");
    }
    public void Listener2(object obj, PropertyChangedEventArgs args)
    {
        Console.WriteLine("2");
    }
}

    static void Main(string[] args)
    {
        var mediator = new Mediator();
        var sender = new Sender(mediator);
        mediator.Trigger();

        Console.WriteLine("EOT");
        Console.ReadLine();
    }

Edit 3

As an comment to all argument about misuse of direct event invoking -- misuse is of course still possible. All it takes is implementing the described above workaround.

Edit 4

Small sample of my code (end use), Dan please take a look:

public class ExperimentManager : INotifierPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string property_name)
    {
        PropertyChanged.Raise(this, property_name);
    }

    public enum Properties
    {
        NetworkFileName,
        ...
    }

    public NotifierChangedManager<string> NetworkFileNameNotifier;
    ...

    public string NetworkFileName
    {
         get { return NetworkFileNameNotifier.Value; }
         set { NetworkFileNameNotifier.Value = value; }
    }

    public ExperimentManager()
    {
        NetworkFileNameNotifier =
            NotifierChangedManager<string>.CreateAs(this, Properties.NetworkFileName.ToString());
        ...
    }


Think about it for a second before going off on a rant. If any method could invoke an event on any object, would that not break encapsulation and also be confusing? The point of events is so that instances of the class with the event can notify other objects that some event has occurred. The event has to come from that class and not from any other. Otherwise, events become meaningless because anyone can trigger any event on any object at any time meaning that when an event fires, you don't know for sure if it's really because the action it represents took place, or just because some 3rd party class decided to have some fun.

That said, if you want to be able to allow some sort of mediator class send events for you, just open up the event declaration with the add and remove handlers. Then you could do something like this:

public event PropertyChangedEventHandler PropertyChanged {
    add {
        propertyChangedHelper.PropertyChanged += value;
    }
    remove {
        propertyChangedHelper.PropertyChanged -= value;
    }
}

And then the propertyChangedHelper variable can be an object of some sort that'll actually fire the event for the outer class. Yes, you still have to write the add and remove handlers, but it's fairly minimal and then you can use a shared implementation of whatever complexity you want.