Extension methods are defined as static methods, but they are called through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. The extension method cannot, of course, break the concept of object-oriented encapsulation, so it can only access the public members of the extended class.
extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special static method, but it can be called just like an instance method on an extended type.
C # extension method The first parameter specifies which type the method acts on, and the parameter is prefixed with the This modifier.
The purpose of an extension method is to add a method to an existing type, which can be either a data type such as int,string or a custom data type.
An understanding of how to add a method to a data type: Generally speaking, the int data type has a ToString method, which is to convert the int data to the type of the string, for example, now we want to add a bit of something when converting to a string, such as adding a character a. Then the previous ToString is not good, because it is just it our int data is converted to a string type, but it is not possible to add a letter A. So this is going to use the so-called extension method.
First, let's look at a way to add an extension to an existing type.
We want to add an Add method to the string type, which is the function of adding a letter A to the strings.
public
static
class
test
{
public
static
int
CountYourNumber(
this
string
str)
{
return
str.Split(
new
char
[] {
‘ ‘
,
‘.‘
,
‘?‘
},
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
The important requirements of the extension method are as follows:
- The class that declares the extension method must be declared as static.
- The extension method itself must be declared as static.
- The extension method must contain the keyword this as its first parameter type, followed by the name of the class that it extends.
It is also important to note that C # only supports extension methods, does not support extended properties, extended events, and so on.
C # Extension methods