C# language feature:
applies to
benefit
how to use
public static class
with desired name.this
keyword.Notes
example:
namespace CodeSage.ExtensionMethod // 1) Declare namespace in new class file.
{
// 2) Declare a `public static class` with desired name.
public static class Extension_Method_Example
{
// 3) Declare a method and precede the first parameter of class being extended with `this` keyword.
static public bool HasSpace(this String str) // String is the class being extended
{
return !(str.IndexOf(' ') == -1);
}
}
}
// to use an extension method
namespace CodeSage.ExtensionUse
{
// 4) Add using namespace and reference extension method on class being "extended".
using CodeSage.ExtensionMethod;
public class Use_of_Extension_Method
{
public void test()
{
String sometext = "Hi I have a space"; // 5) Declare and Call the extended method
bool result = sometext.HasSpace();
}
}
}