#808 – Adding Parameters to an Extension Method

When you define an extension method, the first parameter of your method represents the instance that you want the method to act upon.  You can, however, add additional parameters.

An extension method that acts on a string, for example, would have string as the first parameter and then, optionally, some other parameters.

        public static string Decorate(this string s, string frontDec, string backDec)
        {
            return frontDec + " " + s + " " + backDec;
        }

When you invoke the method, you pass in these additional parameters.

            // Using the extension method
            string s = "Salk announces polio vaccine";
            string dec = s.Decorate("<<==", "==>>");
            Console.WriteLine(dec);

808-002

Notice that Intellisense now lists the new extension method as an option for the string type and correctly lists two parameters.
808-001

Advertisements