C # Operator Overloading

Source: Internet
Author: User

Operators generally refer to the +,-, *,/, and other symbols used for arithmetic operations. Since we have made provisions on the compiler, it is easy for the compiler to recognize these operations. However, some things cannot be connected through "+" because the system is not defined, so we need to overload the operators.

Overload:Programming LanguageMultiple method names are allowed, but their methods (functions) have different parameters and return types, so their processing methods are different.

So what is Operator overload? Let's give an example.

If we create a custom class: window, then define two variables window 1 and window 2 and instantiate them, then what is window 1 + window 2? The first thing that comes to mind for beginners is: two windows. But the system does not know, so we must reload the operator "+" and then implement our operations. Let us add it to return to the sky or window.

Public static void main () {window a = new window {Weight = 50}; window B = new window {Weight = 100}; console. writeline (a + B);} public class window {public decimal weight {Get; set;} public static decimal operator + (window A1, window A2) {return a1.weight + a2.weight }}

Through the overload of the "+" operator, we can calculate the result of adding two windows. This is just a preliminary understanding of the C # 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.