Subscribe to MentalFloss Minutes        RSS Feed
-----

Actual Programming Post - Events

Icon Leave Comment
EDIT: Screw all that
class Concept2
{
    public event EventHandler Explode = delegate { };

    public void Test()
    {
        // Still no null check.
        Explode(this, new EventArgs());
    }
}



Much better...


[OBSOLETE BUT PRESERVED FOR HISTORY]
I had an epiphany here just a moment ago about events. Anyone who finds flaw in my thinking please let me know because this is how I will always do things from now on until someone tells me it's wrong.

When you read about events, there's always all the talk about checking for it being null.

public void Demonstration()
{
    if (DemonstrationCompleted != null)
    {
        DemonstrationCompleted(this, new EventArgs());
    }
}



Then you have the threaded debacle... so you have to write it like this:

public void Demonstration()
{
    DemonstrationCompletedEventHandler local = DemonstrationCompleted;
    if (local != null)
    {
        local(this, new EventArgs());
    }
}



Pointless as far as I can tell.

using System;

namespace EventExperiment
{
    class Concept
    {
        // General event:
        public event EventHandler OnComplete;

        // Constructor registers event to self:
        public Concept()
        {
            OnComplete += new EventHandler(Concept_OnComplete);
        }

        // Boom - never have to check for null again.
        private void Concept_OnComplete(object sender, EventArgs e)
        {
        }

        // Public interface that fires event. Notice no null check:
        public void DoSomething()
        {
            OnComplete(this, new EventArgs());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Concept c = new Concept();
            // Notice no registration to event:
            c.DoSomething();

            c.OnComplete += new EventHandler(c_OnComplete);


            // No errors... no problems. completely issolated and clean.

            Console.ReadLine();
        }

        // Just to show...
        private static void c_OnComplete(object sender, EventArgs e)
        {
            Console.WriteLine("Concept code completed.");
        }
    }
}



Have fun.

0 Comments On This Entry

 

May 2013

S M T W T F S
      1234
567891011
12131415161718
1920212223 24 25
262728293031 

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    0 user(s) viewing

    0 Guests
    0 member(s)
    0 anonymous member(s)