#391 – Passing a Delegate Instance as a Parameter

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;
        }

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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: