C # Extension methods

Source: Internet
Author: User

An extension method is a special static method that does not have to create a new derived class and recompile the original type.

Example: Judging whether it is a weekend or a working day

New DateTime (42); Switch (datetime.dayofweek) {     case  dayofweek.saturday:    case  DayOfWeek.Sunday:        returntrue;     default :         return false ;}

If you want to reduce the duplication of code, you can write helper classes

 Public Static classdatetimehelper{ Public Static BOOLisweekend (datetime datetime) {Switch(datetime.dayofweek) { CaseDayofweek.saturday: CaseDayOfWeek.Sunday:return true; default:                return false; }    }}

Call

if (datetimehelper.isweekend (date))    Weekendprocessing (); Else     weekdayprocessing ();

To use the extension method:

 Public Static classdatetimeextensions{ Public Static BOOLIsweekend ( Thisdatetime datetime) {        Switch(datetime.dayofweek) { CaseDayofweek.saturday: CaseDayOfWeek.Sunday:return true; default:                return false; }    }}

The difference is that one of the parameters of the method needs to use the This keyword, which indicates that the extended class also needs to be aware that a static method must not be the same as the existing method signature

Call:

New DateTime (44); if (date. Isweekend ())    weekendprocessing (); Else     weekdayprocessing ();

The Isweekend () method is used as part of the DateTime method to accumulate the method and the convenience.

Don't forget to go in when you finally use the namespace of the extension class

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.