Created
February 12, 2013 11:26
-
-
Save mrmikejones/4761687 to your computer and use it in GitHub Desktop.
Example of using delegates in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace DelegateExample | |
{ | |
public class MyClass | |
{ | |
delegate float MyDelegate(float input); | |
MyDelegate DelegateFunction; | |
public void Initialise(bool square) | |
{ | |
if(square) | |
{ | |
DelegateFunction = new MyDelegate(SquareFunction); | |
} | |
else | |
{ | |
DelegateFunction = new MyDelegate(DoubleFunction); | |
} | |
} | |
public float DoCalculation(float input) | |
{ | |
return DelegateFunction(input); | |
} | |
float DoubleFunction(float input) | |
{ | |
return input * 2.0f; | |
} | |
float SquareFunction(float input) | |
{ | |
return input * input; | |
} | |
} | |
public class MyTest | |
{ | |
static void Main(string[] args) | |
{ | |
MyClass myClass = new MyClass(); | |
myClass.Initialise(true); | |
Console.WriteLine(string.Format("Result: {0}", myClass.DoCalculation(3.0f))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment