"Inside C #" note (11) operator overloading

Source: Internet
Author: User

Operator overloading is similar to the previous indexer in order to make the language itself easier to use directly, and also as a syntactic sugar.

One operator overload (Operator overloading)

The existence of operator overloading allows existing operators to be redefined and manipulated to manipulate user-defined data types. Operator overloading is only a syntactic sugar, because its essence is actually a call to a method and does not add new features to the language itself.

A) syntax for operator overloading

public static < return value >operator< operator > (< parameter 1>,< parameter 2> ...)

There are some rules:

Must be modified with public static

The type of the return value is not restricted, but it is not recommended to return a bool type.

The number of arguments depends on the nature of the overloaded operator, and if it is a unary operator, a parameter is also required for overloading, as well as $ two for two.

When you overload a unary operator, the type of the parameter must be the current class.

Overloading the two-tuple operator requires that the type of the first parameter is the current class, and the second parameter type does not have a limit.

b) operators that can be overloaded

Unary operators: +,-,!, ~,++,--, true,false

Binary operators: +,-, *,/,%,&,|,^,<<,>>,==,!=,>,<,>=,<=

c) equals cannot be overloaded, but if the two-tuple operator is overloaded, the corresponding combination operator, such as +=,-=, is also equivalent to being overloaded.

[], and () also cannot be overloaded.

d) in order to ensure the readability of the code, only when the actual need to reload the reload.

Learning materials: Inside C # by Tom Archer

"Inside C #" note (11) operator overloading

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.