#391 – Passing a Delegate Instance as a Parameter
August 17, 2011 Leave a comment
When you use the delegate keyword to define a delegate, you’re actually defining a new class, which inherits from System.MulticastDelegate.
public delegate string StringProcessorDelegate(string input);
When you declare a variable of this delegate type and assign a method to it, you’re creating an instance of the new class.
StringProcessorDelegate stringProcessor = ReverseAndHighLight;
static string ReverseAndHighLight(string input)
{
// Reverse, add asterisks
}
You now have a delegate instance that is set up to invoke the ReverseAndHighlight method. This instance is actually just a normal .NET object, since it’s an instance of the new type that derives from System.MulticastDelegate. This means that you can pass this object to a method, as a parameter.
string result = DoStringProcessing(stringProcessor, "Basil Rathbone");
static string DoStringProcessing(StringProcessorDelegate del, string input)
{
Console.WriteLine("Input string: {0}", input);
string result = del(input);
Console.WriteLine("Result: {0}", result);
return result;
}
