| title | Delegates and Events | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| actions |
|
||||||||
| material |
|
Tag: C# Basics
We have previously used Runtime.Notify () method to broadcast information when something happens in the contract. See the line:
Runtime.Notify (someAlien.Id, "created");According to the documentation, the method triggers an event that accepts any number of parameters. In this case, the event method accepted a BigInteger type and a string type.
In this chapter, we will learn how to define custom events, and raise them in the contract.
A delegate holds a reference to a method (or methods). They can refer to any method with a particular parameter list and return type. They can be declared similar to a method declaration:
delegate void OperationDelegate (int x, int y); The delegate, OperationDelegate, can be used as a reference variable to any methods that have two int parameters and returns void.
There are many uses for delegate types, and this tutorial will only focus on the basics. The example below uses a delegate to point to two methods at the same time:
delegate void OperationDelegate (int x, int y);
static void Multiply (int x, int y)
{
Console.Writeline (x * y);
}
static void Divide (int x, int y)
{
Console.Writeline (x / y);
}
public static void Main ()
{
// Initiates a delegate 'Operation' and points to the multiply method
OperationDelegate Op = new OperationDelegate (Multiply);
// Adds a reference to another method
Op += Divide;
// Invokes the delegate
Op (10, 2);
}You can see that a delegate can be invoked similar to a method. The main method prints "20" and "5" at the same time.
Events are a special type of delegates. The 'publisher' of an event is the class that defines the event, and invokes it, in the same way that OperationDelegate Op is invoked above. Here is an example:
event OperationDelegate OperationEvent;
// Invokes the event
OperationEvent (int1, int2); Here, OperationEvent is of type OperationDelegate. That means that it can refer to any method or delegate with the same parameter signatures as OperationDelegate: two int parameters and returns void.
That way, if another class or program wants to do something when OperationEvent is invoked, they can add something like this in their code.
OperationEvent += OpHandler;
static void OpHandler (int x, int y)
{
// Runs when OperationEvent is invoked
}-
Create a
publicdelegate calledAlienUpdateDelegatewithvoidreturn type and one parameter of typeBigInteger. -
Create
staticevents calledAlienGeneratedandAlienDeletedwhose signature delegates are bothAlienUpdateDelegate -
Replace
Runtime.Notify ()call inGenerateAlien ()with the eventAlienGenerated. Pass in the alien id as parameter.