Event Handling in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Nishant Gaurav
    New Member
    • Jul 2010
    • 17

    #1

    Event Handling in C#

    Hi All,

    I want to create a event on a static variable of the class.
    The intention is to notify the class whenever the static variable value is changed, so that it can do some processings.

    Please help me do this.
    Thanks & Regards
    Nishant Guarav
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    Have a look at properties, you can build the event raiser from the set block. eg:

    Code:
    private static int _ANumber = 5;
    
    public static int ANumber
    {
      get { return _ANumber; }
      set 
      {
        _ANumber = value;
        //Event would be fired here.
      }
    }

    Comment

    • Nishant Gaurav
      New Member
      • Jul 2010
      • 17

      #3
      thanks AmzBee for the response, i did the same thing but was not able to get the event handler respond to that, when the static value was changed in some other class.
      It will be of great help if u can show it with a example how this can be done.

      Thanks & Regards
      Nishant Gaurav

      Comment

      • Christian Binder
        Recognized Expert New Member
        • Jan 2008
        • 218

        #4
        Hi!

        Please provide the code you've actually written, so I'd be able to find out what you've done wrong.

        Who do you want to notify when the property's value is changed? The static class or any instance of this class?

        Comment

        • Aimee Bailey
          Recognized Expert New Member
          • Apr 2010
          • 197

          #5
          Be aware that firing events outside of a form will most likely cause a cross-thread exception, im taking a stab in the dark that your trying to update a form?

          Aimee.

          Comment

          • Nishant Gaurav
            New Member
            • Jul 2010
            • 17

            #6
            yes AmzBee, u r spot on on this.
            Let me clear the scenario once again.

            Code:
            namespace asd
            {
            class abc //my main class running the form is running
            {
              // the variable for which i want to create a listener.
              public static int i;
              
              // function that i want to call once the change in value is notified by event listener
              public void fn()
              {
              }
            
            }
            }
            
            // this is a library which is called by some other class
            using asd;
            namespace dsa
            {
            Class lib
            {
              public static setvalue()
              {
                // will be able to change the value of abc class variable i as it is static.
                abc.i =10;
                /// once this value is set i want to notify abc class about the change. Which inturn will call the function fn().
              }
            }
            
            }
            any Help on this thing will be of great help.
            If there is some another way of doing this, i want to know that too..

            i want the most efficient way of doing this thing.

            Thanks & Regards
            Nishant Gaurav

            Comment

            • Aimee Bailey
              Recognized Expert New Member
              • Apr 2010
              • 197

              #7
              To be honest this area is a quite clouded one, and ive found many people find it hard to deal with events in c#, id reccomend checking out MDSN on the topic of events and delegates, however as im in the giving mood hehe, here is the most elegant way to handle events within static classes:

              This is the external static class:
              Code:
              public static class clsTest
                  {
                      public delegate void MyEventHandler(string message, DateTime when);
                      public static event MyEventHandler MyEvent;
              
                      static clsTest()
                      {
                          // Adds our internal subscriber.
                          MyEvent += new MyEventHandler(clsTest_MyEvent);
                      }
              
                      static void clsTest_MyEvent(string message, DateTime when)
                      {
                          // Events require atleast 1 subscriber.
                      }
              
                      public static void FireEvent(string message)
                      {
                          MyEvent(message, DateTime.Now);
                      }
                  }
              And here is a form i created:
              Code:
              public partial class Form1 : Form
                  {
                      public Form1()
                      {
                          InitializeComponent();
                          clsTest.MyEvent += new clsTest.MyEventHandler(clsTest_MyEvent);
                      }
              
                      void clsTest_MyEvent(string message, DateTime when)
                      {
                          this.BeginInvoke(  new clsTest.MyEventHandler(HandleEvent), message, when );
                      }
              
                      void HandleEvent(string message, DateTime when)
                      {
                          string msg = string.Format("Message: {0} \r\n At: {1}", message, when);
                          MessageBox.Show(msg);
                      }
              
                      private void button1_Click(object sender, EventArgs e)
                      {
                          clsTest.FireEvent("hello");
                      }
              
                  }
              Make note that i actually subscribe to the event twice, this is because an event is required to have atleast one subscriber on initialization.

              Also, to raise the event like in visual basic, all you need do is call the event and pass it the arguments specified in the delegate.

              I know this is a bit of a verbose answer, and il probably be told off for it, but hey if it helps!

              Comment

              • Nishant Gaurav
                New Member
                • Jul 2010
                • 17

                #8
                Hi AmzBee/ChBinder,
                Sorry but i didn't get the info that i intended for.
                Or may be i am not able to understand in what way it is potraying the scenario i informed about.

                For that case let me again specify the need.

                Code:
                namespace abc
                {
                	class asd
                	{
                		public static int x;
                		// want an eventlistener or a way to call a function asd
                		public asd()
                		{
                			//having code to access non static variable so can not be static.
                		}
                		public static void Main()
                		{
                			xyz.setValue();
                		}
                	}
                
                	class xyz
                	{
                		public statis void setValue()
                		{
                			asd.x = 10; // At this instant of time the event should notify 
                			// class asd about the change in value.
                		}
                	}
                }
                Please let me know if i am able to convey u my requirement this time :)

                Comment

                • Christian Binder
                  Recognized Expert New Member
                  • Jan 2008
                  • 218

                  #9
                  Code:
                  class asd {
                      public static event Action<int> XChanged;
                  
                      private static int _x;
                  
                      public static int x {
                        get { return _x; }
                        set {
                          if (value != x) {
                            _x = value;
                            if (XChanged != null)
                              XChanged(x);
                          }
                        }
                      }
                  
                      // Constructor
                      public asd() {
                        XChanged += EventHandlingMethod;
                      }
                  
                      void EventHandlingMethod(int newValue) {
                        // Do something
                      }
                    }
                  
                    class xyz {
                      public void setValue() {
                        asd.x = 1; // the event should be fired after setting x to 1
                      }
                    }

                  Comment

                  • Nishant Gaurav
                    New Member
                    • Jul 2010
                    • 17

                    #10
                    Originally posted by ChBinder
                    Code:
                    class asd {
                        public static event Action<int> XChanged;
                    
                        private static int _x;
                    
                        public static int x {
                          get { return _x; }
                          set {
                            if (value != x) {
                              _x = value;
                              if (XChanged != null)
                                XChanged(x);
                            }
                          }
                        }
                    
                        // Constructor
                        public asd() {
                          XChanged += EventHandlingMethod;
                        }
                    
                        void EventHandlingMethod(int newValue) {
                          // Do something
                        }
                      }
                    
                      class xyz {
                        public void setValue() {
                          asd.x = 1; // the event should be fired after setting x to 1
                        }
                      }
                    Hi chBinder,
                    Thanks for the above code, but
                    the above code gives error at XChanged(x);
                    The error is:
                    System.NullRefe renceException: Object reference not set to an instance of an object.

                    It will be really helpful if u tell me what has gone wrong in this case.

                    Comment

                    • Nishant Gaurav
                      New Member
                      • Jul 2010
                      • 17

                      #11
                      Hi chBinder,
                      Thanks for the above code, but
                      the above code gives error at XChanged(x);
                      The error is:
                      System.NullRefe renceException: Object reference not set to an instance of an object.

                      It will be really helpful if u tell me what has gone wrong in this case.
                      As per the code Xchanged is a public static variab;e so there is no need to create the instance.

                      i am putting here the code that i tested with ur code.
                      Code:
                      namespace StaticEvent
                      {
                          public class VuserData
                          {
                              public static event Action<int> Xchanged;
                      
                              private static int _x;
                      
                              public static int x
                              {
                                  get
                                  {
                                      return _x;
                                  }
                                  set
                                  {
                                      if (value != x)
                                          _x = value;
                                      Xchanged(x);
                                  }
                              }
                      
                              public VuserData()
                              {
                                  Xchanged += new Action<int>(VuserData_Xchanged);
                              }
                      
                              void VuserData_Xchanged(int obj)
                              {
                                  Console.WriteLine("{0}", obj);
                              }
                              public static void Main()
                              {
                                  Test.sMain();
                              }
                          }
                      
                          class Test
                          {
                              public static void sMain()
                              {
                                  VuserData.x = 1;
                              }
                          }
                      }

                      Comment

                      • Christian Binder
                        Recognized Expert New Member
                        • Jan 2008
                        • 218

                        #12
                        On line 20:
                        Xchanged(x);
                        You've to check first, if Xchanged isn't null!

                        Code:
                        if(Xchanged != null)
                          Xchanged(x);

                        Comment

                        • Nishant Gaurav
                          New Member
                          • Jul 2010
                          • 17

                          #13
                          Originally posted by ChBinder
                          On line 20:
                          Xchanged(x);
                          You've to check first, if Xchanged isn't null!

                          Code:
                          if(Xchanged != null)
                            Xchanged(x);
                          In that case the Xchanged(x) is never called.
                          What am i missing over here.

                          Comment

                          • Christian Binder
                            Recognized Expert New Member
                            • Jan 2008
                            • 218

                            #14
                            You never create an object of type VuserData like
                            Code:
                            VuserData obj1 = new VuserData();
                            At least when you create an object of type VuserData it will be attached to the Changed-Event

                            Comment

                            • Aimee Bailey
                              Recognized Expert New Member
                              • Apr 2010
                              • 197

                              #15
                              Read my last reply, give's the valid way of firing events inside of a class.

                              Comment

                              Working...