C# Extension Methods
In this chapter you will learn:
- What are Extension Methods
- Syntax to create Extension Methods
- Example
- Extension methods versus instance methods
Description
Extension methods can extend an existing type with new methods without altering the definition of the original type.
Syntax
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.
Example
For example:
public static class StringHelper
{/*from www . j av a 2 s. c o m*/
public static bool IsCapitalized (this string s)
{
if (string.IsNullOrEmpty(s))
return false;
return char.IsUpper (s[0]);
}
}
The IsCapitalized extension method can be called as though it were an instance method on a string, as follows:
Console.WriteLine ("Java2s".IsCapitalized());
An extension method call, when compiled, is translated back into an ordinary static method call:
Console.WriteLine (StringHelper.IsCapitalized ("Path"));
The translation works as follows:
arg0.Method (arg1, arg2, ...); // Extension method call
StaticClass.Method (arg0, arg1, arg2, ...); // Static method call
Interfaces can be extended too:
public static T First<T> (this IEnumerable<T> sequence)
{/*ww w . ja v a 2s . c o m*/
foreach (T element in sequence)
return element;
throw new InvalidOperationException ("No elements!");
}
Console.WriteLine ("Java2s".First());
The code above generates the following result.
Note
Any compatible instance method will always take precedence over an extension method.
Next chapter...
What you will learn in the next chapter:
- What are C# Properties
- How to create C# Properties
- Example for C# Properties
- Note for properties
- Add statement to the getter and setter of a property
- Put logic to property setter
- throw Exception from property setting