-
Notifications
You must be signed in to change notification settings - Fork 89
Extension methods
This is one of C# 3.0 features, that we've been thinking about since a year or so. The basic idea is to allow users to extend existing classes with methods. One example where it is useful is a list class extending array class with ToList() method.
Extension methods need to be public and static. They can be polymorphic
themselves, but the class that holds them cannot. You currently cannot
place them in nested types. The first parameter of extension method
is a class that is going to be extended, for example to extend the
System.String
class you use:
namespace MyNamespace {
class MyExtensionClass {
public static Capitalize (this s : string) : string
{
s.Substring (0, 1).ToUpper () + s.Substring (1) // or whatever
}
}
}
Now in addition to regular:
using MyNamespace;
_ = MyExtensionClass.Capitalize (my_string)
you can do:
using MyNamespace;
_ = my_string.Capitalize ()
The using
part is necessary.
So all it takes to turn a static method into extension method is a little
this
in front of the first parameter. The method could have other
parameters, like:
public static ChopLast (this s : string, k : int) : string
{
s.Substring (0, s.Length - k)
}
then the usage would be:
_ = my_string.ChopLast (7)
In order to use extension method on generic types, like arrays, one need to define a generic method or non-generic method in generic class. For example:
public static ToList[T] (this a : array [T]) : list [T]
{
// whatever
}
There are cases, when you need more than one type parameter, like:
public static FoldLeft[A,B] (this a : array [A], ini : B, f : A * B -> B) : B
{ ... }
We also can do specializations with extension methods, like:
public static Sum (this a : array [int]) : int
{ ... }