Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sending events for a sender is forbidden in C#?

Tags:

c#

events

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());
        ... 
    }
like image 947
greenoldman Avatar asked Dec 10 '22 14:12

greenoldman


2 Answers

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.

like image 96
siride Avatar answered Dec 29 '22 16:12

siride


Allowing anyone to raise any event puts us in this problem:

@Rex M: hey everybody, @macias just raised his hand!

@macias: no, I didn't.

@everyone: too late! @Rex M said you did, and we all took action believing it.

This model is to protect you from writing applications that can easily have invalid state, which is one of the most common sources of bugs.

like image 37
Rex M Avatar answered Dec 29 '22 16:12

Rex M