Extension methods
Extension methods are static methods that can be invoked using the instance method syntax. In effect extension methods make it possible for us to extend existing types and constructed types with additional methods.
For example, we can define an extension method as follows:
public static class MyExtensions { public static bool IsCandy(this Product p) { if (p.ProductName.IndexOf("candy") >= 0) return true; else return false; } }
In this example the static method, IsCandy,
takes a this
parameter of Product
type and searches for the word, candy,
inside the product name. If it finds a match it assumes this is a candy
product and returns true
. Otherwise it returns false
, meaning this is not a candy
product.
Because all extension methods must be defined in top-level static classes here to simplify the example, we put this class inside the same namespace as our main test application, TestNewFeaturesApp...