Home > C# and dot NET > Delegates C#

Delegates C#

Delegates adalah type yang mempunyai reference pada method dengan parameter dan return type yang sama ( -dengan method ).  Setelah men-inisiasi delegates, kita dapat men-reference delegates tersebut dengan method  yang mempunyai parameter dan return type yang sama dan dapat memanggil method melalui delegates.

Syntax untuk mendeklarasikan delegates.
delegate <return type> <delegate-name> (<parameter list>)

Syntax untuk meninisiasi delegates.

<delegate-name> <delegate-object-name> = new <delegate-name>(<method-name>)
atau
<delegate-name> <delegate-object-name> = <method-name>

Example.

namespace AppBasicConsole
{
delegate int NumberChanger(int inputNumber);
delegate string StringReverse(string inputString);

class Program
{
public static int AddNumber(int inputNumber){
return inputNumber + 5;
}

public static int MultipleNumber (int inputNumber){
return inputNumber * inputNumber;
}

public static string Reverse(string inputString)
{
char[] arrCharacter = inputString.ToCharArray();
Array.Reverse(arrCharacter);
return new string(arrCharacter);
}

static void Main(string[] args)
{
NumberChanger numberChangerOne = AddNumber;
NumberChanger numberChangerTwo = MultipleNumber;
StringReverse stringReverse = Reverse;

Console.WriteLine(numberChangerOne(5));
Console.WriteLine(numberChangerTwo(5));
Console.WriteLine(stringReverse("Indonesia"));
}
}
}

Capture screen.

Delegates

Delegates

Referensi : dari berbagai sumber.
Semoga bermanfaat.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: