Se afișează postările cu eticheta Events. Afișați toate postările
Se afișează postările cu eticheta Events. Afișați toate postările

luni, 25 august 2014

Anonymous Functions in C#

An anonymous function is an inline statement or expression that can be used wherever a delegate type is expected.
An anonymous function has no name.

Types of anonymous functions:
  • Lambda Expressions
  • Anonymous Methods
Example:

delegate void TestAnonymousFunctionDelegate(string s);

// A delegate can be initialized with inline code - anonymous method
TestAnonymousFunctionDelegate del1 = delegate(string s) { MessageBox.Show(s); };
del1("This is anonymous method.");

// A delegate can be initialized with a lambda expression.
TestAnonymousFunctionDelegate del2 = (x) => { MessageBox.Show(x); };
del2("This is lambda expression.");

 
<< Multicast delegates                                                                                              Events >>

Events in C#

An event is a message sent by an object to signal the occurrence of an action. 
An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. 
The most use for events is in graphical user interfaces and the action could be caused by user interaction or it could be triggered by some other program logic.

Example:

// Declare a delegate for an event. 
delegate void EventHandler();
 
class Product
{
public string Name { getset; }
       private int mQuantity;
       public int Quantity 
       {
            get 
            {
                  return mQuantity;
             }
             set 
             {
                    mQuantity = value;
                    OnQuantityChange();
              }
       }

      // Declare event.  
       public event EventHandler QuantityChangeEvent;

       // This is called to fire the event.
       public void OnQuantityChange()
       {
              if (QuantityChangeEvent != null)
                     QuantityChangeEvent();
             }
}

 
static void handler()
{
      MessageBox.Show("Quantity changed!");  
}

Product p = new Product();

//Add handler() to the event list. 
p.QuantityChangeEvent += new EventHandler(handler);
p.Name = "Prod A";
p.Quantity = 10;
p.Quantity = 0;

<< Anonymous functions