C # Learning -- Operator Overloading

Source: Internet
Author: User

 

Operator Overloading means to redefine existing operators and assign them another function to adapt to different data types.

To overload operators, you must useOperatorKeyword, and use the access modifier static to modify. As follows:

View code

 1   Using  System;  2   Using  System. Collections. Generic;  3   Using  System. LINQ;  4   Using System. text;  5   6   Namespace  Leleapplication3  7   {  8       Class  Program  9   {  10           Public   Class  Sum  11  {  12               # Region Members 13               Public   Int  Num1;  14               Public   Int  Num2;  15               # Endregion  16   17               # Region Constructor 18              Public Sum ( Int Number1, Int  Number2)  19   {  20                   This . Num1 = Number1;  21                   This . Num2 = Number2;  22   }  23               # Endregion 24   25               # Region Operator 26               Public   Static Sum Operator + (Sum sum1, sum sum2)  27   {  28                   Return   New Sum (sum1.num1 + sum2.num1, sum2.num2 + Sum1.num2 );  29  }  30               # Endregion  31   32   33   }  34           Static   Void Main ( String  [] ARGs)  35   {  36 Sum sumfirst = New Sum (5 , 6  );  37 Sum sumsecond = New Sum ( 6 , 5  );  38 Sum sumthird = sumfirst + Sumsecond;  39   40 Console. writeline ( "  Sumthird. num1 = {0}, sumthird. num2 = {0} "  , Sumthird. num1, sumthird. num2 );  41   Console. readkey ();  42   }  43   }  44 }

The running result is:

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.