157 recommendations for writing high-quality code to improve C # programs--Recommendation 9: Custom overloaded operators

Source: Internet
Author: User

Recommendation 9: Custom overloaded operators

In the development process, you should be accustomed to using the syntax features that Microsoft provides to us. I think everyone likes to see this grammatical feature:

    int 1 ;       int 2 ;       int

Instead of using the following syntax to do the same thing:

    int 1 ;       int 2 ;       int int

Similarly, when building your own type, we should always consider whether the type can be used for operator overloading. If you consider type salary, the following code looks less comfortable:

    New  A  };       New  -  };      

Type support should be made:

The latter read at a glance. The CLR supports overloading operators in types by defining static member functions using the operator keyword, allowing developers to use the type as if they were built-in primitive types. The version of the salary overloaded "+" operator should look like the following:

    class Salary      {          publicintgetset;}                 Public Static operator +(Salary s1, Salary S2)          {              + = S1. RMB;               return s2;          }      }

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 9: Custom overloaded operators

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.