Extension Methods

This is a special type of static method that has a slightly different syntax.
Extension methods allow you to add methods to existing types without having to derive a new type.
Extension methods are a special kind of static method but they are called as if they were instance methods on the extended type.
You can use extension methods to extend a class or interface but not to override it.
Extension methods are only in scope when you explicitly import the namespace.
Allows you to "add" methods to existing types without creating a new derived class or modifying the original type
msdn.microsoft.com/en-GB/library/bb383977.aspx
What is your extension method has the same name as an existing method name?
An extension method with the same name and signature will never be called as an instance member
It can only be called as a static method


Extension methods are defined as static members
The first parameter specifies which type the method operates on.
This parameter is preceeded by the 'this' modifier.
Extension methods cannot access private variables in the type.
Extension methods must be defined in a static class
You invoke the extension method using instance method syntax



Extensing System.String


For simple types like System.String the extension methods are not shown in the intellisense

namespace ExtensionMethods 
{
   public static class MyExtensions
   {
      public static int WordCount(this System.String str)
      {
         return str.Split(new char[] {' ','.', '?'}, String.SplitOptions.RemoveEmptyEntries).Length
      }
   }
}


LINQ Standard Query Operators

One of the best examples of extension methods is the LINQ standard query operators.



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext