Overview
Extension methods provide syntactical sugar for calling a static method using instance method syntax. This means you can syntactically extend an instance of any object you do not own. As an added bonus, you get full IntelliSense support through the Visual Studio IDE. I must reiterate that this feature is merely syntactical sugar and does not actually offer any new functionality. It does however provide a more elegant mechanism of encapsulating and extending types that you may or may not actually own.
Constraints
Syntax
Extension methods use the ‘this’ keyword for the first parameter to indicate which type they are extending. The extension happens only when the namespace is in scope.
Examples
Here are some contrived examples that I’ve come up with. I am sure you can use your imagination to see where extension methods may come in handy to make the code more concise and clearer.
The object:
1: public sealed class Person
2: {
3: public string FirstName { get; set; }
4: public string LastName { get; set; }
5: public int Age { get; set; }
6: }
The extension:
1: public static string GetName(this Person person)
3: if (string.IsNullOrEmpty(person.FirstName) &&
4: string.IsNullOrEmpty(person.LastName))
5: {
6: return "Anonymous";
7: }
8: else
9: {
10: return string.Concat(person.FirstName, " ", person.LastName).Trim();
11: }
12: }
The usage:
1: Person person = new Person();
2: person.GetName(); // returns "Anonymous";
3: person.LastName = "Smith";
4: person.GetName(); // returns "Smith";
5: person.FirstName = "John";
6: person.GetName(); // returns "John Smith";
You could of course argue that a DisplayName property on the Person object directly would be cleaner. However, the point here is if you do not have access to modify or enhance the original object; we can create a helper method that ‘hangs off’ the actual object to make the code clearer. Here is another example involving the ASP.NET Textbox Web Control.
1: public static bool Validate(this TextBox textbox, string regex, RegexOptions options)
3: return Regex.Match(textbox.Value, regex, options).Success;
4: }
1: if (this.ZipCodeTextBox.Validate("fancy regex", RegexOptions.IgnoreCase) == false)
3: // do something with a failed validation
Please do not take my examples as a standard of when, where and how extension methods should or should not be used. They are contrived examples used only to demonstrate the syntax and potential usage.
Adieu. Navid.