Extension methods

 

Introduction

Extension methods are used to add methods to existing types without creating a derived type, recompiling or modifying the original type.  Extension methods are a particular type of static method that is called as though instance methods on the extended type were concerned.

 

 

Defining an extension method

To define a method as being an extension method, simply select the corresponding operation in the explorer and add the "CsExtensionMethod" without parameters using the icon in the auxiliary window (see below).

 

Adding the "CsExtensionMethod" tagged value to create an extension method

 

Key:

1.      The "CsExtensionMethod" tagged value.

 

 

UML model

C# generated

 

 

 

Example of an extension method defined for the System.String class

 

Note:      An extension method is defined inside a static class that is neither embedded nor generic.