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. This can be used to refer to all sorts of members, ...
Get C# 4.0 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.