extension methods in C #

Source: Internet
Author: User

Extension methods

Add a method dynamically to an existing type without creating a new derived type, recompiling or modifying the source of the original type

An extension method is a special static method that is called in the same way as a normal instance method



? extension Method Use Example

   
 
  1. public static void PrintString(this String val)
  2.   {
  3.   Console.WriteLine(val);
 
    
  
  1. var a Span class= "pun" >= "AAA"
  2. printstring
  3. /span>console readkey

But with our code above, we have "extended" a printstring method to the string type.

(1) Prerequisites

<1> extension methods must be defined in a non-nested, non-generic static class

The <2> extension method must be a static method

<3> extension methods must have at least one parameter

<4> The first parameter must be appended with the This keyword as a prefix

  <5> The first parameter cannot have other modifiers (such as ref or out)

<6> The first parameter cannot be a pointer type

(2) Precautions

<1> as with several of the preceding features, the extension method only increases the compiler's work and does not affect performance (adding attributes to a type in an inherited way can affect performance)

<2> If there is a method in the original class that is the same as your extension method (at least it is the same), then your extension method award will not be called and the compiler will not prompt you

<3> extension methods are too powerful to affect architecture, patterns, readability, etc...

An example of your own writing
   
 
  1. public static class father
  2. {
  3. public static int Speak(this int i) {
  4. Console.WriteLine("this is a test{0}",i);
  5. return i+20;
  6. }
  7. }
 
    
  
  1. int ii = 10;
  2. Console.WriteLine(ii.Speak());

 

From for notes (Wiz)

extension methods in C #

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.