CupCode Gamers
From the Cup, to the Code, for the Gamers
  • News
  • Games and Apps
    • Droplets
    • Jet Fighter
    • Jet Fighter Neon
    • Short Circuit
    • ThaumCheater
    • Tic-Tac-Toe
    • Zombie Swarm
  • Other Pages
    • Itch-IO
    • Steam Group
    • YouTube Channel
    • Facebook
    • Twitter
    • Google+
    • Discord
  • Surviving Ars Magica 2
  • C# Tutorials
  • Support
  • About Us
  • Policies
  • Contact Us

Delegates by Example Part 2

3/27/2017

using System;
/* This example illustrates building one delegate to call several functions in sequence
* The final output of this example will be
*
* WriteOut method called
* 2
* WriteIn method called
* 1
* WriteIn method called
* 0
*
* Notice that even though we pass 1 to the arguments of the delegate, the first iteration of
* WriteIn recieves the value of 2. This is because WriteOut modified that value to 2.
* Using this method, all functions share the same argument, thus if the first function modifies
* it's value, it's modified for all the rest of the functions in the list.
* This is very important in deciding whether to use the method in example1 or example2, as it
* can significantly change the resulting output of the program.
* (NOTE: This is not true on every compiler, test to find out)
*/
namespace DelegatesTutorial
{
class Example2
{
// Declare the delegate to be used later, this sets the return type and expected parameters
// for the delegate. All functions to be included must have the same return type and parameter list.
delegate void MyDelegate(int number);
public Example2()
{
// We'll create a single delegate from MyDelegate and assign WriteOut to it
MyDelegate TheDelegate = new MyDelegate(WriteOut);
// Now add WriteIn to the existing delegate
TheDelegate += new MyDelegate(WriteIn);
// Call the functions of the delegate
TheDelegate(1);
// Remove the WriteOut delegate
TheDelegate -= new MyDelegate(WriteOut);
// Call the functions of the delegate again.
TheDelegate(1);
}
// These are the functions to be called by the delegate
void WriteOut(int number)
{
Console.WriteLine("WriteOut method called");
int i = ++number;
Console.WriteLine(i.ToString());
}
void WriteIn(int number)
{
Console.WriteLine("WriteIn method called");
int i = --number;
Console.WriteLine(i.ToString());
}
}
}


Respond

Copyright © 2017 CupCode Gamers / Jason Yarber