Binary Operators
This lesson takes a look at the binary operators in C# in detail using coding examples.
In the previous lesson you studied unary operators, in addition to those C# has binary operators as well that form expressions of two variables. The example below shows how to use the binary operators.
Binary Operators Example
Press + to interact
using System;class Binary{public static void Main(){int x, y;float result;x = 9;y = 4;result = x+y; //additionConsole.WriteLine("x+y: {0}", result);result = x-y; //subtractionConsole.WriteLine("x-y: {0}", result);result = x*y; //multiplicationConsole.WriteLine("x*y: {0}", result);result = x/y; //divisionConsole.WriteLine("x/y: {0}", result);result = (float)x/(float)y; //casting int to float and then performing divisionConsole.WriteLine("x/y: {0}", result);result = x%y; //modulusConsole.WriteLine("x%y: {0}", result);result += x; //assignment with operationConsole.WriteLine("result+=x: {0}", result);}}
Code Explanation
The example above shows several examples of binary operators. As you might expect, the results of
- addition (
+
) - subtraction (
-
) - multiplication (
*
) - division (
/
)
produce the expected mathematical results.
-
In the code the
result
variable is a floating point type. -
We explicitly cast the integer variables
x
andy
to calculate a floating point value in line 25. -
There is also an example of the remainder(
%
) operator.- It performs a
Get hands-on with 1400+ tech skills courses.