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; //addition
Console.WriteLine("x+y: {0}", result);
result = x-y; //subtraction
Console.WriteLine("x-y: {0}", result);
result = x*y; //multiplication
Console.WriteLine("x*y: {0}", result);
result = x/y; //division
Console.WriteLine("x/y: {0}", result);
result = (float)x/(float)y; //casting int to float and then performing division
Console.WriteLine("x/y: {0}", result);
result = x%y; //modulus
Console.WriteLine("x%y: {0}", result);
result += x; //assignment with operation
Console.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 and y 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.