Delegates

A delegate is a special type, where you can store a reference to a function. With delegates you change the way how you work, and somehow reverse it. Give it a function, and after that you give if the requested values for that function, and process it.

Why? So you can assign an action (or maybe with if’elses or a for loop, different actions) and then after that give it the values and process it. Even you might not understand it yet completely, this makes code easier, and things possible that maybe wouldn’t be possible without this.

This sounds a bit crazy, but lucky enough it’s rather easy, you just need to understand it. Nothing better than some example to make you understand!

[ad#Adsense]

Just create a new console application and use the following code, code is provided with comments that should make you understand.

namespace DelegatesFTW
{
class Program
{
// First we create a new delegate
delegate int ourMathDelegate(int value1, int value2);
static int Multiply(int tomulti1, int tomulti2)
{
return tomulti1 * tomulti2;
}
static int Add(int toadd1, int toadd2)
{
return toadd1 + toadd2;
}
static void Main(string[] args)
{
ourMathDelegate process;
Console.WriteLine("Enter your first number");
int number1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your secund number");
int number2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter M if you want to multiply or A if you want to Add the numbers toghether!");
string input = Console.ReadLine();
if (input == "M")
process = new ourMathDelegate(Multiply);
else
process = new ourMathDelegate(Add);
Console.WriteLine("Result: {0}", process(number1, number2));
Console.ReadKey();
}
}
}

* We used a lot of different names for the values, to show you the power of this, you don’t need to have the same names, it’s almost like magic!

Still got no clues? Ask in comment where your brain goes wrong, and I will reply and modify the article to make it better!

CategoriesITTags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.