c# delegate vs action code example
Example 1: C# delegate
using System;
public class CargoAircraft
{
// Create a delegate type (no return no arguments)
public delegate void CheckQuantity();
// Create an instance of the delegate type
public CheckQuantity ProcessQuantity;
public void ProcessRequirements()
{
// Call the instance delegate
// Will invoke all methods mapped
ProcessQuantity();
}
}
public class CargoCounter
{
public void CountQuantity() { }
}
class Program
{
static void Main(string[] args)
{
CargoAircraft cargo = new CargoAircraft();
CargoCounter cargoCounter = new CargoCounter();
// Map a method to the created delegate
cargo.ProcessQuantity += cargoCounter.CountQuantity;
// Will call instance delegate invoking mapped methods
cargo.ProcessRequirements();
}
}
}
Example 2: delegate c# mvc
using System;
namespace MVC
{
public class Book
{
// declare a delegate for the bookpricechanged event
public delegate void BookPriceChangedHandler(objectsender,
BookPriceChangedEventArgs e);
// declare the bookpricechanged event using the bookpricechangeddelegate
public event BookPriceChangedHandlerBookPriceChanged;
// instance variable for book price
object _bookPrice;
// property for book price
public object BookPrice
{
set
{
// set the instance variable
_bookPrice=value;
// the price changed so fire the event!
OnBookPriceChanged();
}
}
// method to fire price canged event delegate with proper name
// this is the method our observers should be implenting!
protected void OnBookPriceChanged()
{
BookPriceChanged(this, new BookPriceChangedEventArgs(_bookPrice));
}
}
}