C# 3.0 Extension Methods
(Page 1 of 4 )
In this eighth part of a ten-part series on C#, you will learn about extension methods and anonymous types; we will also begin to look at attributes. It is excerpted from chapter four of
C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Extension Methods (C# 3.0)
Extension methods allow an existing type to be extended with new methods without altering the definition of the original type. An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended. For example:
public static class StringHelper
{
public static bool IsCapitalized (this string s)
{
if (string.IsNullOrEmpty(s)) return false;
return char.IsUpper(s[0]);
}
}
TheIsCapitalizedextension method can be called as though it were an instance method on a string, as follows:
Console.WriteLine("Perth".IsCapitalized());
An extension method call, when compiled, is translated back into an ordinary static method call:
Console.WriteLine(StringHelper.IsCapitalized("Perth"));
The translation works as follows:
arg0.Method(arg1, arg2, ...); //
extension method call
StaticClass.Method(arg0, arg1, arg2, ...); // static method call
Extension Method Chaining
Extension methods, like instance methods, provide a tidy way to chain functions. Consider the following two functions:
public static class StringHelper
{
public static string Pluralize (this string s) {...}
public static string Capitalize (this string s) {...}
}
x andyare equivalent and both evaluate to"Sausages", butxuses extension methods, whereasyuses static methods:
string x = "sausage".Pluralize().Capitalize();
string y = StringHelper.Capitalize (StringHelper.Pluralize("sausage")));
Next: Ambiguity and Resolution >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|