157 recommendations for writing high-quality code to improve C # programs--Recommendation 101: Using extension methods to "add" methods to existing types

Source: Internet
Author: User

Recommendation 101: Use extension methods to "add" methods to existing types

Consider how to have a new behavior for a sealed type. We used to create a wrapper class and then add a method to it, which doesn't look elegant at all. We might consider modifying the design, modifying the sealed type directly, and then publishing a new version for it, but it relies on you having all the source code. More often, we will take the approach of programming to APIs provided by third-party companies. For us, the FCL is the best API that a group of third-party companies (Microsoft) provides to us.

The packaging class is encoded as follows:

    classProgram {Static voidMain (string[] args) {Student Student=NewStudent ();        Console.WriteLine (studentconverter.getsexstring (student)); }    }     Public Static classStudentconverter { Public Static stringgetsexstring (Student Student) {returnStudent. Getsex () = =true?"male":"female"; }    }
    Class Student    {        boolfalse;}}   

As you can see, the student type only provides a Getsex method that returns the result of a bool value. What we need is to convert a bool value to a string, Studentconverter is a wrapper class created to satisfy the requirements. The caller's code should look like this:

Console.WriteLine (studentconverter.getsexstring (student));

But we know that there can be a more graceful form for callers to invoke getsexstring like an instance method called the student type. The better way is to extend the method:

classProgram {Static voidMain (string[] args) {Student Student=NewStudent (); Console.WriteLine (student.        Getsexstring ()); }    }     Public Static classstudentextension { Public Static stringGetsexstring ( ThisStudent Student) {            returnStudent. Getsex () = =true?"male D":"A woman?"; }    }

The extension method has some other major advantages in addition to calling the extension method to invoke the method as it would call the type itself:

    • Can extend the sealing type;
    • You can extend the types in a third-party assembly;
    • The extension method avoids the unnecessary depth inheritance system.

The extension method also has some requirements that must be followed:

    • The extension method must be in a static class, and the class cannot be a nested class;
    • The extension method must be static;
    • The first parameter of an extension method must be the type to be extended, and the This keyword must be added;
    • Extended properties, events are not supported.

It is important to note that the extension method can also extend the interface. This makes the interface appear to be extensible as well. This feature of extension methods is widely used in enumerable classes and queryable classes that provide LINQ query functionality. For example, enumerable provides a very rich method for the Ienumerable<t> interface, such as select:

 Public Static Ienumerable<tresult> Select<tsource, tresult> ( This ienumerable<tsource> source, Func< TSource, tresult>// specific code omitted    }

It is equivalent to having a select method for any subclass that inherits from the Ienumerable<t> interface, and these select methods appear to the user as if they were declared by the Ienumerable<t> interface.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 101: Using extension methods to "add" methods to existing types

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.