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

Delegates by Example Part 1

3/27/2017

using System;
using System.Collections.Generic;

/* This example shows how you can use delegates in a generic list to call several methods in sequence
 * The final output of this tutorial will be:
 *
 * WriteOut method called
 * 2
 * WriteIn method called
 * 0
 *
 * As you see, the methods are called in the order they were added to the generic list.
 * Also note that the value of the argument is the same for each call, that's because using this
 * method, you are supplying the value seperately to each function in the delegate.
 */
namespace DelegatesTutorial
{
    class Example1
    {
        // 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 Example1()
        {
            // We'll create a generic array of delegates
            List TheDelegates = new List();
            // Now we'll add the functions to the delegate array list
            TheDelegates.Add(new myDelegate(WriteOut));
            TheDelegates.Add(new myDelegate(WriteIn));
            // Here we'll loop through every delegate in the list, calling it's associated function
            foreach (myDelegate simple in TheDelegates)
            {
                simple(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 © 2020 CupCode Gamers / Jason Yarber

Privacy Policy