O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required