본문 바로가기

Software/C#.Net

Extension Method

extension methods allow existing compiled types (specifically, classes, structures, or interface implementations) as well as types currently being compiled (such as types in a project that contains extension methods) to gain new functionality without needing to directly update the type being extended.
+extension method must be declared with the static keyword
+all extension methods are marked as such by using the this keyword 
+every extension method can be called either from the correct instance in memory or statically via the defining static class! 
*if you do not explicitly import the correct namespace, the extension methods are not available for that C# code file
 
Example
 
Declare a class
public class Car 
{ 
  public int Speed; 
  public int SpeedUp() 
  { 
    return ++Speed; 
  } 
} 
another class, trying to call a member of the Car class
public static class CarExtensions 
{ 
  public static int SlowDown(this Car c) 
  { 
    // Error! This method is not deriving from Car! 
    return --Speed; 
  } 
} 

To success,
public static class CarExtensions 
{ 
  public static int SlowDown(this Car c) 
  { 
    // OK! 
    return --c.Speed; 
  } 
}