Extension Method, c # Extension Method

Source: Internet
Author: User

Extension Method, c # Extension Method

 

The extension method enables you to "add" methods to existing types without creating a new derived type, re-compiling, or modifying the original type in other ways. An extension method is a special static method, but it can be called like an instance method of an extension type. (Derived from csdn)

It may be better understood with an example

Extension Method:

Public static class Helper {public static bool IsNullOrEmpty (this string str) {return string. IsNullOrEmpty (str );}}View Code

Usage:

 

Static void Main (string [] args) {Console. Write ("qwe". IsNullOrEmpty (); Console. ReadKey ();}View Code

 

 

The extension method must be static class or static method. Why is it static? You can see the source code.

The extension method is actually a static method call.

Bytes ---------------------------------------------------------------------------------------------------------------------------

When an instance object has a method with the same name as the extension method, what method will it perform?

Public static class Helper {public static void Miao () {Console. writeLine ("I am the kitten of the Extension Method");} public class Cat {public void Miao () {Console. writeLine ("I Am a kitten from an instance ");}}View Code static void Main (string [] args) {Cat c = new Cat (); c. Miao (); Console. ReadKey ();}View Code

It can be seen that the compiler will give priority to finding the Miao method in the Cat class during compilation. If the Miao method is found, the execution method will be executed. If the method is not found, the extension method will be searched and executed.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.