473,405 Members | 2,282 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Fun with delegates and events

Hi everybody,

I am currently working on a C# project, but I am kind of stuck. If anybody can give me a hand with this I would really appreciate it.

We are trying to build an application with a user GUI. When I click button1 I want to call another method to do some work and when it is done, it should callback via a delegate. Unfortunately it is giving me the error “Object reference not set to an instance of an object.”. This should not be too complicated, but somehow I am not able to resolve this myself.

This is my code:

=== BEGIN GUI CODE ===
Expand|Select|Wrap|Line Numbers
  1. public delegate void ButtonsServerTreeViewDelegate(object sender);
  2. private void button1_Click(object sender, EventArgs e)
  3. {
        // Setup listener, for updating the GUI...
  4.     DiscTreeView DiscTreeViewObject = new DiscTreeView();
  5.     DiscTreeViewObject.ButtonsServerTreeView += new ButtonsServerTreeViewDelegate(CallbackButtonsServerTreeView);
  6.  
  7.   //  DiscTreeViewObject.LoadServerTreeView();
  8.     PathSelectionTreeView.LoadServerTreeView();}
  9.  
  10. public void CallbackButtonsServerTreeView(object sender)
  11. {
        label31.Text = "HI";
    }
=== END GUI CODE ===

==== BEGIN OTHER CLASS CODE ====
Expand|Select|Wrap|Line Numbers
  1. public event ButtonsServerTreeViewDelegate ButtonsServerTreeView;
  2. public void LoadServerTreeView()
  3. {
       ButtonsServerTreeView(this);
    }
==== END OTHER CLASS CODE ====

Note that the LoadServerTreeView is called with PathSelectionTreeView and not with the DiscTreeViewObject (commented out), since PathSelectionTreeView contains my TreeView.

Is there anyway to perform the callback, if I call my LoadServerTreeView via PathSelectionTreeView ?

Again, any help is greatly appreciated.

Warm Regards,

Jan
Aug 29 '08 #1
3 920
balabaster
797 Expert 512MB
At what line are you getting that exception? It seems that you are referencing a property or method of an object that you haven't instantiated or is currently set as null or nothing...
Aug 29 '08 #2
Now I know that the exception occurs because ButtonsServerTreeView is null. I know how to prevent the event from being send, but is there some kind of way I can send events from the LoadServerTreeView ?
Aug 31 '08 #3
vekipeki
229 Expert 100+
Actually, you MUST check if your event is non-null before invoking it - the usual way is to do it like this:

Expand|Select|Wrap|Line Numbers
  1.       public event ButtonsServerTreeViewDelegate ButtonsServerTreeView;
  2.       public void LoadServerTreeView()
  3.       {
  4.              ButtonsServerTreeViewDelegate handler = ButtonsServerTreeView;
  5.              if (handler != null)
  6.                  handler(this);
  7.       }
The whole point of using events is that your event-firing class should never know or care who and when will subscribe to any of its events (e.g. a button control has many events but in most cases you will only handle the MouseClick event).

Also note that the event handler in code snippet above is first referenced by a temporary handler variable, to avoid a race condition when another thread can unsubscribe from your event just after you have checked that it is not null. This way your still have a valid reference to a handler which gets executed anyway.

Another solution would be to create an empty delegate instance in your delegate chain just to assure that your event is never null:

Expand|Select|Wrap|Line Numbers
  1.       public event ButtonsServerTreeViewDelegate ButtonsServerTreeView = delegate { };
  2.       public void LoadServerTreeView()
  3.       {
  4.              ButtonsServerTreeView(this);
  5.       }
The latter solution gives a slight overhead when executing it, but makes your code slightly cleaner. And it's easier to just go through your existing code and add " = delegate {}; " to all your events :o).
Aug 31 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Marty McDonald | last post by:
It is still unclear to me why we would use events when delegates seem to do just fine. People say that events make it so the publisher doesn't need to know about the listeners. What does that...
0
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can...
4
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on...
3
by: Chris | last post by:
Hi, what is the difference between using events and delegates (apart from the syntax) ? have a look at following (working) programs please (you can just copy/paste and build it) : First...
4
by: Tim | last post by:
There are a set of clients who need to be notified of certain events. I have used events and delegates (publisher-Subscriber model) for the notification mechanism. All the clients register with...
30
by: Burkhard | last post by:
Hi, I am new to C# (with long year experience in C++) and I am a bit confused by the language construct of events. What is it I can do with events that I cannot do with delegates? At the moment...
2
by: kristian.freed | last post by:
Hi, I currently work in a project written fully in C# where we make extensive use of delegates and events. We have a model where a "state", an object holding data but not much code but which...
5
by: raylopez99 | last post by:
I understand delegates (static and non-static) and I agree they are very useful, and that the "Forms" used in the Windows .NET API could not work without them. That said, I'm curious as to how...
7
by: Siegfried Heintze | last post by:
I'm studying the book "Microsoft Visual Basic.NET Language Reference" and I would like some clarify the difference between events and delegates. On page 156 I see a WinForms example of timer that...
9
by: raylopez99 | last post by:
Hello all— I’m trying to get the below to work and cannot get the format right. It’s from this example: http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx What it is: I’m trying...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.