C # Programming Guide (5) Extension Method)

Source: Internet
Author: User

C #3.0 introduces new features. The extension method can greatly increase the beauty of your code, and the extension method provides your extension. NET Framewoke class extension path, writing and rules are also simple.

 

 

There are several requirements for writing extension methods:

First, the class of the extension method must be global and cannot be an internal nested class.

Second, the class of the extension method is static.

Third, the extension method is static.

Fourth: the data type of the first parameter of the extension method must be the extension type.

Fifth: The first parameter of the extension method uses the this keyword.

 

 

The following is a simple code:

 

  1 using System;
2  using System.Collections.Generic;
3  using System.Linq;
4  using System.Text;
5
6  namespace ExtensionMethod
7 {
8 public static class TestClass
9 {
10 public static void Print(this int i)
11 {
12 Console.WriteLine(i);
13 }
14
15 public static int Times(this int i)
16 {
17 return i * 2;
18 }
19
20 public static int Add(this int i, int d)
21 {
22 return i + d;
23 }
24 }
25
26 class Program
27 {
28 static void Main(string[] args)
29 {
30 int number = 4;
31 number.Print();
32 Console.WriteLine(number.Times());
33 Console.WriteLine(number.Add(5));
34 }
35 }
36 }

 

 

 

The code is very simple. It is extended to the int type.

The first is to define a Print method, which is an extension method without parameters and no return values.

The second is to define an extension method with a return value without parameters.

The third is to define an extension method with parameters that return values.

 

Sample Code: Download

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.