An extension method is a static method of a static class that can be invoked using the instance method syntax. Extension methods are used to add new behaviors to an existing type without altering. In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.
Conceptually, extension methods provides as an implementation of the decorator structural pattern. At compile time an extension method call is translated into an ordinary static method call.
We want to extend the string object with a new function WordCount
- //defining extension method
- public static class MyExtensions
- {
- public static int WordCount(this String str)
- {
- return str.Split(new char[] { ' ' }).Length;
- }
- }
- class Program
- {
- public static void Main()
- {
- string s = "I am Extension Method";
- int i = s.WordCount();
- Console.WriteLine(i);
- }
- }
No comments:
Post a Comment