Defining Extension Methods

Back to our string reversal example to show how we can enable the instance-method-looking invocation syntax for our extension to the System.String type. Compared to the original helper class and method code we wrote before, the only difference is to put a this modifier on the first parameter of the method:

static class StringExtensions{    public static string Reverse(this string s)    {        var chars = s.ToCharArray();        Array.Reverse(chars);        return new string(chars);    }}

In C#, the this keyword is used in no fewer than four different places, most of which we still have to discuss. Here’s an overview:

To refer to the current instance of an object. You can use this to ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.