For this article, I will demonstrate How to use delegates using a very simple C# example.
Let's create a sample function and named it as ParseString.
static string ParseString(string str)
{
return str.Replace("'", "");
}
Declare the delegate for the ParseString function.
public delegate string DelegateParser(string str);
Now instantiate the delegate and invoke the function through the delegate.
string mystring = Console.ReadLine();
//Instantiate the delegate
DelegateParser parser = new DelegateParser(ParseString);
//Call the delegate
Console.WriteLine(parser(mystring));
That's how simple it is. Here is the complete code:
static string ParseString(string str)
{
return str.Replace("'", "");
}
public delegate string DelegateParser(string str);
static void Main(string[] args)
{
string mystring = Console.ReadLine();
DelegateParser parser = new DelegateParser(ParseString);
Console.WriteLine(parser(mystring));
Console.ReadKey();
}
I often often use delegates to encapsulate my libraries so that actual functions names are not visible to other programmers. This is an effective way to standardize coding.
For more C# tips and tricks, subscribe now
0 comments:
Post a Comment