C # Extension methods

Source: Internet
Author: User

C # Extension methods

I. Extension methods:

1. What is the extension method and what is the role?

Extension methods enable you to "add" methods to an existing type without having to create a new derived type, recompile, or otherwise modify the original type in one way. It still maintains object-oriented features.

2. Features of the extension method:

Static class;

static method;

this keyword;

The class to extend;

parameter (optional)

3. Extension Method Example:

As developers know, customers often change demand, so to be a good programmer must make the programs we develop scalable. Due to the change in requirements below need to give mycalculate class extension a method: Subtract method, the common method is to modify the class of mycalculate directly, if you have the source is good, then if not, will not be helpless, in fact, we do not have to worry about, We can worry about others have thought of, this is the legendary-extension method.

Called in the class:

class program    {        staticvoid Main (string[] args)        {            varNew  mycalculate ();             var sub = My. Subtract (3);            Console.WriteLine (sub);            Console.readkey ();        }    }

class to extend the method:

   Public class mycalculate    {        publicstaticint Add (intint  num2)        {             return num1 + num2;        }    }

Extended classes:

 Public  Static class mycalculateextension    {       publicstaticint Subtract ( This mycalculate my,int  int  num2)       {          return num1- num2;       }    }

C # Extension methods

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.