Public · Protected · Private
About delegates and Events
Type: Public  |  Created: 2008-08-22  |  Frozen: Yes
« Previous Public Blog Next Public Blog »
Comments
  • Here I create a simple class public class myclass { //member public int X = 10; //method public int Y() { if (zee != null) return zee(); else return 10; } //delegate public delegate int Z(); //event public event Z zee; } All I have ia a member,method,delegate and event watch how we use each of them....
    2008-08-22 13:06
  • //in your main() add this code myclass m = new myclass(); // for data you can directly grab int a = m.X; This is a direct use .. no explanation
    2008-08-22 13:10
  • // for methods you need to execute int b = m.Y(); // for methods you need to execute int b = m.Y(); //For delegates you need instance of method and then execute it. myclass.Z z = m.Y; // do you see we used myclass.Z instead of m.Z?!! int c = z();
    2008-08-22 13:27
  • Let me add couple of code in the class that has main() // own delegate public delegate int Z(); // Own method public int y100() { MessageBox.Show("100"); return 100; } //Own method public int y200() { MessageBox.Show("200"); return 200; }
    2008-08-22 13:28
  • Now I add following code in main() after earlier code .......... //For your own delegate freely instantiate -- same as above and execute it. Z z1 = m.Y; int d = z1(); // This returns 10-10-10-10 MessageBox.Show(a.ToString() + "-" + b.ToString() + "-" + c.ToString() + "-" + d.ToString());
    2008-08-22 13:29
  • m.zee += this.y100; c = z(); // This returns 10-10-100-10 MessageBox.Show(a.ToString() + "-" + b.ToString() + "-" + c.ToString() + "-" + d.ToString()); m.zee += this.y200; c = z(); // This returns 10-10-200-10 MessageBox.Show(a.ToString() + "-" + b.ToString() + "-" + c.ToString() + "-" + d.ToString()); m.zee -= this.y200; c = z(); // This returns 10-10-100-10 MessageBox.Show(a.ToString() + "-" + b.ToString() + "-" + c.ToString() + "-" + d.ToString()); // This doesn't return error (even if this.y200 is not part of the event) m.zee -= this.y200; c = z(); // This returns 10-10-100-10 MessageBox.Show(a.ToString() + "-" + b.ToString() + "-" + c.ToString() + "-" + d.ToString());
    2008-08-22 13:30
  • Basically Event creates a place for an arraylist of pointers to execute. Each pointer is a type of the specified delegate. That is why //delegate public delegate int Z(); //event public event Z zee; and our fundamental method has calls public int Y() { if (zee != null) return zee(); else return 10; } If you read design patterns -- and see OBSERVER patterns -- that is EVENT!! Delegate makes it simpler to use functio pointers. so that functions can be instantiated and executed.
    2008-08-22 13:35
This blog is frozen. No new comments or edits allowed.