How to check if already subscribed to event?

I have a .NET 3.5 winforms app with the following:

public class Class1{
....
myInstance.TheEvent += new EventHandler (myInstance_TheEvent);
...
}

The above is in a method that might be called more than once.  I can't put the above in Class1's constructor because myInstance isn't created at that time.  There's a particular workflow that is followed, which causes myInstance to be created after the constructor call.  I'd like to check if

myInstance.TheEvent == null

and subscribe only for that case.  However, that conditional is not legal.  How else can I check if myInstance has already subscribed to TheEvent?
brettrAsked:
Who is Participating?
 
käµfm³d 👽Commented:
I'm actually not sure (and very curious) as to why that is. It could possibly be due to the way I implemented the OnEvent event.

However, that was not the intended use of OnEvent. The private event is the one you should be checking for null. The public event is more just for show. See the code posted below just to reassure that a private event will be fired/handled.
//////////////////////////////////////////////////
// Main
//////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Class1 c = new Class1();
 
            c.OnEvent += new EventHandler(c_OnEvent);
            c.AProperty = "test";
            c.AProperty = "test2";
 
            Console.ReadKey();
        }
 
        static void c_OnEvent(object sender, EventArgs e)
        {
            Console.WriteLine("Event raised!!");
        }
    }
}
 
//////////////////////////////////////////////////
// Class 1
//////////////////////////////////////////////////
using System.Collections.Generic;
 
using System;
 
namespace ConsoleApplication1
{
    class Class1
    {
        private string someData;
 
        private List<EventHandler> subscribedEvents;
        private event EventHandler _OnEvent;
        public event EventHandler OnEvent
        {
            add
            {
                if (!this.subscribedEvents.Contains(value))
                {
                    this._OnEvent += value;
                    this.subscribedEvents.Add(value);
                }
            }
            remove
            {
                if (this.subscribedEvents.Contains(value))
                {
                    this._OnEvent -= value;
                    this.subscribedEvents.Remove(value);
                }
            }
        }
 
        public Class1()
        {
            this.subscribedEvents = new List<EventHandler>();
        }
 
        public string AProperty
        {
            set
            {
                this.someData = value;
                onEventRaise();
            }
        }
 
        private void onEventRaise()
        {
            if (this._OnEvent != null)
            {
                this._OnEvent(this, new EventArgs());
            }
        }
    }
}

Open in new window

0
 
käµfm³d 👽Commented:
Wherever in your code that you raise the event, that is where you check for null:
public class Test
{
    private string testString;
    public event EventHandler TestEvent;
 
    public Test()
    {
        this.testString = string.Empty;
    }
 
    public string TestProperty
    {
        get
        {
            return this.testString;
        }
 
        set
        {
            this.testString = value;
 
            if (this.TestEvent != null)
            {
                this.TestEvent(this, new EventArgs());
            }
        }
    }
}

Open in new window

0
 
brettrAuthor Commented:
There are many other subscribers so that will not handle this particular instance.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
käµfm³d 👽Commented:
The event is not marked static, so there is a separate event for each instance of the class. Perhaps I'm not following what you are referring to.
0
 
JackOfPHCommented:
I don't know how in C# but in vb this is what I usually do...

If not me.TestEvent is  nothing then

end if

or

If not me.Testevent is system.dbnull.value then

end if


I hope you get my idea...

0
 
brettrAuthor Commented:
@kaufmed

Ok, sorry.  The event is in a singleton.  So, it will have multiple subscribers.

@JackOfPH

That's was my initial approach.  Unfortunately, C# will complain about that type of checking, as mentioned above.
0
 
käµfm³d 👽Commented:
Would exposing another property work:
public bool IsWired
{
    get { return (this.OnEvent != null); }
}
 
 
// Consumer
 
if (!class.IsWired)
{
    class.Event += new EventHandler();
}

Open in new window

0
 
brettrAuthor Commented:
No because again, this is in a singleton.  this.OnEvent might have 10 different subscribers, where the above Class1 is #10.
0
 
käµfm³d 👽Commented:
Ok, I'm not trying to be thick, I've just never written my own singleton.

What if you did something like such (where you raise the private event in code--the public event is just for checking the list):
private List<EventHandler> subscribedEvents;
private event EventHandler _OnEvent;
public event EventHandler OnEvent
{
    add
    {
        if (!this.subscribedEvents.Contains(value))
        {
            this._OnEvent += value;
            this.subscribedEvents.Add(value);
        }
    }
    remove
    {
        if (this.subscribedEvents.Contains(value))
        {
            this._OnEvent -= value;
            this.subscribedEvents.Remove(value);
        }
    }
}

Open in new window

0
 
brettrAuthor Commented:
@kaufmed:
When I try your code, I can no longer raise the event:

private void onEventRaise()
        {
            if (OnEvent!= null)
            {
                OnEvent(this, new EventArgs());
            }
        }

I get this compiler error:

The event 'OnEvent' can only appear on the left hand sie of += or -=

Is there another way to raise it?
0
 
käµfm³d 👽Commented:
I don't see anything that relates to that error message in the code you posted. Is that the code that is highlighted by compiler when error occurs?
0
 
brettrAuthor Commented:
Yes.  It highlights these two lines:

if (OnEvent!= null)
            {
                OnEvent(this, new EventArgs());
0
 
brettrAuthor Commented:
Create a console app and paste the following into it to see the error:
namespace ConsoleApplication1
{
    class Class1
    {
        static void Main(string[] args)
        {
        }
 
        private List<EventHandler> subscribedEvents;
        private event EventHandler _OnEvent;
        public event EventHandler OnEvent
        {
            add
            {
                if (!this.subscribedEvents.Contains(value))
                {
                    this._OnEvent += value;
                    this.subscribedEvents.Add(value);
                }
            }
            remove
            {
                if (this.subscribedEvents.Contains(value))
                {
                    this._OnEvent -= value;
                    this.subscribedEvents.Remove(value);
                }
            }
        }
 
        private void onEventRaise()
        {
            if (OnEvent != null)
            {
                OnEvent(this, new EventArgs()); 
            }
        }
    }
}

Open in new window

0
 
käµfm³d 👽Commented:
I take it that gave you what you were looking for?
0
 
brettrAuthor Commented:
Yes, I'm also curious why the public event didn't work on null check.

Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.