[.net] new to event handling, so I got errors!

Started by
3 comments, last by maxdub 16 years, 5 months ago
I understand the basics of delegates, I just dont know how to 'cause' the event, Im missing something here. The goal is to have an event occur. This is a console app.

using System;
using System.Collections.Generic;
using System.Text;

namespace event_handling
{
    public class myEventArgs : EventArgs
    {
        public myEventArgs(string s)
        {
            myname = s;     
        }
        private string myname;             
    }

    public delegate void mydelegate(object o, myEventArgs e);

    public class listner
    {
        publisher mypublisher;

        public listner(publisher p)
        {
            mypublisher = p;

            //connect p's event object to the delegate to the function to call on event occuring
            p.eventhappening += new mydelegate(fark);
            
            //event += new delegate(function to call on event);
        }

        public void fark(object o, EventArgs e)
        {
            Console.WriteLine("HOLY FARK IT WORKED!");
        }
    }
    public class publisher
    {
        public event mydelegate eventhappening;
        public publisher()
        {
            //create the args object that will be passed
            myEventArgs e = new myEventArgs("jason");
            
            if (eventhappening != null)
            {
                eventhappening(this, e);//raise the event
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            publisher pblshr = new publisher();
            listner lstnr = new listner(pblshr);
            EventArgs e = new EventArgs();
            object o = new object();
            
            //pblshr.eventhappening(o, e);//gives error about only appearing on the left side of += or -=
            Console.ReadLine();

            
        }
    }
}

Advertisement
Only the class itself can raise the event.
i have a few questions after reading your code. maybe i just over looked something but why do you have this line:


if (eventhappening != null)
{
eventhappening(this, e);//raise the event
}

i would imagine eventhappening would always be null since this code is in the constructor of the class.

also why are you calling pblshr.eventhappening when you attached fark to the lstnr's version of eventhappenening. I don't theyre the same.. are they?

http://msdn2.microsoft.com/en-us/library/17sde2xt.aspx
.max
"i would imagine eventhappening would always be null since this code is in the constructor of the class."

I suppose so, logic error on my part. I just wanted to make sure it being null or not was checked.

Hey it works.

I made a public void RaiseEvent() function, and moved that code there. Calling it triggers the event. Cool man.

awesome gj. :D
.max

This topic is closed to new replies.

Advertisement