Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Delegates and Events

Delegates and Events

Scheduled Pinned Locked Moved C#
csharpdatabaselinqhelp
7 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • B Offline
    B Offline
    BobInNJ
    wrote on last edited by
    #1

    I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program: using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } } In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. Bob

    L Y P N 4 Replies Last reply
    0
    • B BobInNJ

      I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program: using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } } In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. Bob

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Hi Bob, When your Main (or any other code) wants to do something to stock1, it should set one of its properties, or call one of its methods. events are meant to be used the other way around; they exist for the external world (Main) to be signaled by something that happens inside your class (Stock), as in:

      class MyForm : Form {
      public MyForm() {
      Button btn=new Button();
      this.Controls.Add(btn);
      btn.Click+=new EventHandler(myClickHandler);
      ...
      public void myClickHandler(object sender, EventArgs e) {
      // whatever this form wants to happen when the button detects it is being clicked
      }
      }

      and the Button class would contain something like:

      if (a click got detected) {
          if (this.Click!=null) this.Click(this, new EventArgs()); // execute all the delegates that were
                    // added to the Click event
      }
      

      so it is Button who executes its own event, and MyForm who subscribed to it by adding its myClickHandler to the public event. And all this holds true for .NET, not just for C#. :)

      Luc Pattyn [Forum Guidelines] [My Articles]


      I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


      1 Reply Last reply
      0
      • B BobInNJ

        I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program: using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } } In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. Bob

        Y Offline
        Y Offline
        Yuri Vital
        wrote on last edited by
        #3

        For triging event in C# you have to do more like :

         public static void Main()
            {
                Stock stock1 = new Stock();
                //Add "listener" to you event
                stock1.OnAlert += new Stock.StockPiraceAlertHandler(stock1_OnAlert);
                // test your event by doing this
                stock1.Alert();
        
            }
        
             //When the Alert event will be fired, this function will be called.
            static void stock1_OnAlert(object source, StockArgs a)
            {
                // Put your triger logic here
            }
        
        1 Reply Last reply
        0
        • B BobInNJ

          I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program: using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } } In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. Bob

          P Offline
          P Offline
          PIEBALDconsult
          wrote on last edited by
          #4

          The Main class should not tell the Stock class to raise its event. It can be done, but it's not a good design. Usually we see this error when a derived class tries to raise the event of a base class; I've never seen anyone try to do what you are trying to do.

          1 Reply Last reply
          0
          • B BobInNJ

            I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program: using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } } In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. Bob

            N Offline
            N Offline
            N a v a n e e t h
            wrote on last edited by
            #5

            Stock class owns those events. Main is just a subscriber who will get notification when the event occurs. To get event notification, you need to subscribe to it first.

            public static void Main()
            {
            Stock stock1 = new Stock();
            stock1.OnAlert += AlertOccured; // Subscribing event.
            stock1.Alert(); // This will call Alert() method which will trigger OnAlert event.
            }

            private void AlertOccured(object source, StockArgs a)
            {
            // your code.
            }

            Delegates are the backbone of events. The main difference is events can be raised only by the class which declares them where a delegate instance can be invoked by anyone who have access to it. Following example shows what I meant.

            public delegate void ADelegate();
            class Foo
            {
            public ADelegate ADelegateInstance;

            public void FireADelegate()
            {
                if (ADelegateInstance != null)
                    ADelegateInstance();
            }
            

            }

            class Program
            {
            static void AMethod()
            {
            Console.WriteLine("AMethod()");
            }

            static void Main(string\[\] args)
            {
                Foo f = new Foo();
                f.ADelegateInstance += AMethod;
                f.ADelegateInstance();   // This is valid and calls AMethod
            }
            

            }

            Now if you change public ADelegate ADelegateInstance to public event ADelegate ADelegateInstance the code won't compile. f.ADelegateInstance() is invalid here. If you are following the standard void method(object, EventArgs) pattern for events, you don't have to create your own delegates. Use the EventHandler<T> provided with framework. Your code can be written like,

            public class Stock {

             public event EventHandler<StockArgs> OnAlert;
             public event EventHandler<StockArgs> OnVolumeAlert;
            
             public void Alert()
             {
                 if ( OnAlert != null )
                   OnAlert( this, new StockArgs("ORCL", "14.50", 100000) );
             }
            

            }

            :)

            Best wishes, Navaneeth

            Y 1 Reply Last reply
            0
            • N N a v a n e e t h

              Stock class owns those events. Main is just a subscriber who will get notification when the event occurs. To get event notification, you need to subscribe to it first.

              public static void Main()
              {
              Stock stock1 = new Stock();
              stock1.OnAlert += AlertOccured; // Subscribing event.
              stock1.Alert(); // This will call Alert() method which will trigger OnAlert event.
              }

              private void AlertOccured(object source, StockArgs a)
              {
              // your code.
              }

              Delegates are the backbone of events. The main difference is events can be raised only by the class which declares them where a delegate instance can be invoked by anyone who have access to it. Following example shows what I meant.

              public delegate void ADelegate();
              class Foo
              {
              public ADelegate ADelegateInstance;

              public void FireADelegate()
              {
                  if (ADelegateInstance != null)
                      ADelegateInstance();
              }
              

              }

              class Program
              {
              static void AMethod()
              {
              Console.WriteLine("AMethod()");
              }

              static void Main(string\[\] args)
              {
                  Foo f = new Foo();
                  f.ADelegateInstance += AMethod;
                  f.ADelegateInstance();   // This is valid and calls AMethod
              }
              

              }

              Now if you change public ADelegate ADelegateInstance to public event ADelegate ADelegateInstance the code won't compile. f.ADelegateInstance() is invalid here. If you are following the standard void method(object, EventArgs) pattern for events, you don't have to create your own delegates. Use the EventHandler<T> provided with framework. Your code can be written like,

              public class Stock {

               public event EventHandler<StockArgs> OnAlert;
               public event EventHandler<StockArgs> OnVolumeAlert;
              
               public void Alert()
               {
                   if ( OnAlert != null )
                     OnAlert( this, new StockArgs("ORCL", "14.50", 100000) );
               }
              

              }

              :)

              Best wishes, Navaneeth

              Y Offline
              Y Offline
              Yuri Vital
              wrote on last edited by
              #6

              You have explained such better than me ! :-D

              N 1 Reply Last reply
              0
              • Y Yuri Vital

                You have explained such better than me ! :-D

                N Offline
                N Offline
                N a v a n e e t h
                wrote on last edited by
                #7

                Thanks :thumbsup:

                Best wishes, Navaneeth

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups