Extension Method
You can add methods to existing and custom types without creating a new derived type or modifying the original type in other ways.
An extension method is a special static method, which is defined in a static class, but can be called on objects of other types (the class we want to extend) like calling an instance method, therefore, the extension method can be used to supplement the functions of a class without modifying a class.
Create Extension Method
The extension method is similar to the definition of a general static method. The only difference is that this keyword is added before the first parameter, and the type of the first parameter also determines the type that can be extended by the extension method.
Format
Public static return type Extension Method Name (this refers to the type sourceObj to be extended [, extension method parameter list])
Features of extension methods
1: The extension method is to add a method to the existing type.
2: The Extension Method modifies the first parameter of the method by specifying the this keyword.
3: The extension method must be declared in the static class.
4: The extension method is called by objects.
5. The extension method can contain parameters.
Instance
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace _ 10_ExpandMethod
{
Public static class AddClass
{
// Extend the existing String type
Public static string GetLower (this String str)
{
Return str. ToLower ();
}
// Extended custom Studengt type
Public static string GetName (this Student stu, string strName)
{
Return strName;
}
}
// Custom Student type
Public class Student
{
}
Class Program
{
Static void Main (string [] args)
{
String strURL = "HTTP: // WWW. BAIDU. COM ";
StrURL = strURL. GetLower ();
Console. WriteLine (strURL );
String strName = "Xiaoqiang ";
Student student = new Student ();
Console. WriteLine (student. GetName (strName ));
Console. ReadKey ();
}
}
}
Run