Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 62819
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T18:32:08+00:00 2026-05-10T18:32:08+00:00

I’m using C#, .NET 3.5. I understand how to utilize events, how to declare

  • 0

I’m using C#, .NET 3.5. I understand how to utilize events, how to declare them in my class, how to hook them from somewhere else, etc. A contrived example:

public class MyList {     private List<string> m_Strings = new List<string>();     public EventHandler<EventArgs> ElementAddedEvent;      public void Add(string value)     {         m_Strings.Add(value);         if (ElementAddedEvent != null)             ElementAddedEvent(value, EventArgs.Empty);     } }  [TestClass] public class TestMyList {     private bool m_Fired = false;      [TestMethod]     public void TestEvents()     {         MyList tmp = new MyList();         tmp.ElementAddedEvent += new EventHandler<EventArgs>(Fired);         tmp.Add('test');         Assert.IsTrue(m_Fired);     }      private void Fired(object sender, EventArgs args)     {         m_Fired = true;     } } 

However, what I do not understand, is when one declares an event handler

public EventHandler<EventArgs> ElementAddedEvent; 

It’s never initialized – so what, exactly, is ElementAddedEvent? What does it point to? The following won’t work, because the EventHandler is never initialized:

[TestClass] public class TestMyList {     private bool m_Fired = false;      [TestMethod]     public void TestEvents()     {         EventHandler<EventArgs> somethingHappend;         somethingHappend += new EventHandler<EventArgs>(Fired);         somethingHappend(this, EventArgs.Empty);         Assert.IsTrue(m_Fired);     }      private void Fired(object sender, EventArgs args)     {         m_Fired = true;     } } 

I notice that there is an EventHandler.CreateDelegate(…), but all the method signatures suggest this is only used for attaching Delegates to an already existing EventHandler through the typical ElementAddedEvent += new EventHandler(MyMethod).

I’m not sure if what I am trying to do will help… but ultimately I’d like to come up with an abstract parent DataContext in LINQ whose children can register which table Types they want ‘observed’ so I can have events such as BeforeUpdate and AfterUpdate, but specific to types. Something like this:

public class BaseDataContext : DataContext {     private static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> m_ObservedTypes = new Dictionary<Type, Dictionary<ChangeAction, EventHandler>>();      public static void Observe(Type type)     {         if (m_ObservedTypes.ContainsKey(type) == false)         {             m_ObservedTypes.Add(type, new Dictionary<ChangeAction, EventHandler>());              EventHandler eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;             m_ObservedTypes[type].Add(ChangeAction.Insert, eventHandler);              eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;             m_ObservedTypes[type].Add(ChangeAction.Update, eventHandler);              eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;             m_ObservedTypes[type].Add(ChangeAction.Delete, eventHandler);         }     }      public static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> Events     {         get { return m_ObservedTypes; }     } }   public class MyClass {     public MyClass()     {         BaseDataContext.Events[typeof(User)][ChangeAction.Update] += new EventHandler(OnUserUpdate);     }      public void OnUserUpdated(object sender, EventArgs args)     {         // do something     } } 

Thinking about this made me realize I don’t really understand what’s happening under the hod with events – and I would like to understand 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T18:32:09+00:00Added an answer on May 10, 2026 at 6:32 pm

    I’ve written this up in a fair amount of detail in an article, but here’s the summary, assuming you’re reasonably happy with delegates themselves:

    • An event is just an "add" method and a "remove" method, in the same way that a property is really just a "get" method and a "set" method. (In fact, the CLI allows a "raise/fire" method as well, but C# never generates this.) Metadata describes the event with references to the methods.

    • When you declare a field-like event (like your ElementAddedEvent) the compiler generates the methods and a private field (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you’re referring to the field. Outside the class, you’re referring to the field.

    • When anyone subscribes to an event (with the += operator) that calls the add method. When they unsubscribe (with the -= operator) that calls the remove.

    • For field-like events, there’s some synchronization but otherwise the add/remove just call Delegate.Combine/Remove to change the value of the auto-generated field. Both of these operations assign to the backing field – remember that delegates are immutable. In other words, the autogenerated code is very much like this:

      // Backing field // The underscores just make it simpler to see what's going on here. // In the rest of your source code for this class, if you refer to // ElementAddedEvent, you're really referring to this field. private EventHandler<EventArgs> __ElementAddedEvent;  // Actual event public EventHandler<EventArgs> ElementAddedEvent {     add     {         lock(this)         {             // Equivalent to __ElementAddedEvent += value;             __ElementAddedEvent = Delegate.Combine(__ElementAddedEvent, value);         }     }     remove     {         lock(this)         {             // Equivalent to __ElementAddedEvent -= value;             __ElementAddedEvent = Delegate.Remove(__ElementAddedEvent, value);         }     } } 
    • The initial value of the generated field in your case is null – and it will always become null again if all subscribers are removed, as that is the behaviour of Delegate.Remove.

    • If you want a "no-op" handler to subscribe to your event, so as to avoid the nullity check, you can do:

      public EventHandler<EventArgs> ElementAddedEvent = delegate {}; 

    The delegate {} is just an anonymous method which doesn’t care about its parameters and does nothing.

    If there’s anything that’s still unclear, please ask and I’ll try to help!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 61k
  • Answers 62k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer Assuming you have properly indexed the table that the select… May 11, 2026 at 9:56 am
  • added an answer I believe this is more of an ASP.NET issue and… May 11, 2026 at 9:56 am
  • added an answer Squeak includes all the classic MVC classes, but you can… May 11, 2026 at 9:56 am

Related Questions

I keep getting tasks that are above my skill level. How can I address this without coming accross as grossly incompetent?
I have a web-service that I will be deploying to dev, staging and production.
I'm thinking of starting a wiki, probably on a low cost LAMP hosting account.
I have the following tables in my database that have a many-to-many relationship, which
I'm using the RESTful authentication Rails plugin for an app I'm developing. I'm having
I recently printed out Jeff Atwood's Understanding The Hardware blog post and plan on
I find that getting Unicode support in my cross-platform apps a real pain in
I would like to test a string containing a path to a file for
I'm getting this problem: PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable
I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.