Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do static events compare to non-static events in C#?

I just realized static events exist - and I'm curious how people use them. I wonder how the relative comparison holds up to static vs. instance methods. For instance, a static method is basically a global function. But I've always associated events with instances of objects and I'm having trouble thinking of them at the global level.

Here some code to refer to if it helps an explanation:

void Main()
{
    var c1 = new C1();
    c1.E1 += () => Console.WriteLine ("E1");
    C1.E2 += () => Console.WriteLine ("E2");
    c1.F1();
}

// <<delegate>>+D()
public delegate void D();

// +<<event>>E1
// +<<class>><<event>>E2
// +F()
//      <<does>>
//          <<fire>>E1
//          <<fire>>E2
public class C1
{
    public void F1()
    {
        OnE1();
        OnE2();
    }
    public event D E1;
    private void OnE1()
    {
        if(E1 != null)
        {
            E1();
        }
    }
    static public event D E2;
    static private void OnE2()
    {
        if(E2 != null)
        {
            E2();
        }
    }
}
like image 861
Aaron Anodide Avatar asked Aug 12 '11 19:08

Aaron Anodide


People also ask

What is difference between static and non static function in C?

As we know that non-static functions are global by default means that the function can be accessed outside the file also, but if we declare the function as static, then it limits the function scope. The static function can be accessed within a file only.

What is the difference between static and non static methods?

Static method uses complie time binding or early binding. Non-static method uses run time binding or dynamic binding. A static method cannot be overridden being compile time binding. A non-static method can be overridden being dynamic binding.

What is the use of static method in non static class C#?

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name.

What is the difference between static method and instance method in C#?

Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class. Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.

What is the difference between static methods and events?

For instance, a static method is basically a global function. But I've always associated events with instances of objects and I'm having trouble thinking of them at the global level. Show activity on this post. Be wary of static events.

What are static and non-static methods in C #?

Static and Non-Static Methods in C#. In this quick article you will take a look at static and non-static methods in C#. MSDN Definition: A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, we cannot use the new keyword to create a variable of the class type.

What is the difference between static functions and static classes?

Such functions can access only static variables. The static functions exist even before the object is created. A static class cannot be instantiated and can only contain static members. Static methods is set using static keyword −

What are some interesting facts about static variables in C?

Following are some interesting facts about static variables in C. 1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is...


3 Answers

Be wary of static events. Remember that, when an object subscribes to an event, a reference to that object is held by the publisher of the event. That means that you have to be very careful about explicitly unsubscribing from static events as they will keep the subscriber alive forever, i.e., you may end up with the managed equivalent of a memory leak.

like image 195
Ed S. Avatar answered Oct 20 '22 07:10

Ed S.


Much of OOP can be thought of in terms of message passing.

A method call is a message from the caller to the callee (carrying the parameters) and a message back with the return value.

An event is a message from the source to the subscriber. There are thus potentially two instances involved, the one sending the message and the one receiving it.

With a static event, there is no sending instance (just a type, which may or may not be a class). There still can be a recipient instance encoded as the target of the delegate.

like image 15
Ben Voigt Avatar answered Oct 20 '22 07:10

Ben Voigt


In case you're not familiar with static methods

You're probably already familiar with static methods. In case you're not, An easy-to-understand difference is that you don't need to create an instance of an object toi use a static method, but you DO need to create an instance of an object to call a non-static method.

A good example is the System.IO.Directory and System.IO.DirectoryInfo classes.

The Directory class offers static methods, while the DirectoryInfo class does not.

There are two articles describing them here for you to see the difference for yourself.

http://visualcsharptutorials.com/2011/01/system-io-directory-class/

http://visualcsharptutorials.com/2011/01/system-io-directoryinfo-class/

Now on to static events...

However, static events are seldom seen in the wild. There are very few cases that I can think opf where I'd actually want to use one, but there is a CodeProject article that does show one potential use.

http://www.codeproject.com/KB/cs/staticevent.aspx

The key thought here is taken from the explanation (bold added by me to point out the relevant text):

We saw this property as a separate object and we made sure that there is only one instance of it at a time. And all instances of transactions knew where to find it when needed. There is a fine difference though. The transactions will not need to know about the changes happening on the exchange rate, rather they will use the last changed value at the time that they use it by requesting the current value. This is not enough when, for example, we want to implement an application where the user interface reacts immediately on changes in the UI characteristics like font, as if it has to happen at real-time. It would be very easy if we could have a static property in the Font class called currentFont and a static method to change that value and a static event to all instances to let them know when they need to update their appearance.

As .NET developers we're trained to work with a disconnected model. Think of ADO.NET compared to classic ADO. IN a VB6 app, you could use data controls that would allow the following functionality: If you were running the app on your PC, the data in your grid would update when someone on another PC edited the data.

This isn't something that .NET developers are used to. We're very used to the disconnected model. Static events enable a more "connected" experience. (even if that experience is something we're not used to any more.)

like image 4
David Avatar answered Oct 20 '22 08:10

David