C# Tutorial C# Advanced C# References

C# - assignment operators example



The example below shows the usage of assignment and compound assignment operators:

  • = Assignment operator
  • += Addition AND assignment operator
  • -= Subtraction AND assignment operator
  • *= Multiply AND assignment operator
  • /= Division AND assignment operator
  • %= Modulo AND assignment operator
using System;

class MyProgram {
  static void Main(string[] args) {
    float a = 25;

    Console.WriteLine("a = "+ a);

    //Addition AND assignment operator
    a += 5;
    Console.WriteLine("a += 5; makes a = "+ a);

    //Subtraction AND assignment operator
    a -= 8;
    Console.WriteLine("a -= 8; makes a = "+ a);

    //Multiply AND assignment operator
    a *= 4;
    Console.WriteLine("a *= 4; makes a = "+ a);

    //Division AND assignment operator
    a /= 2;
    Console.WriteLine("a /= 2; makes a = "+ a);

    //Modulo AND assignment operator
    a %= 7;
    Console.WriteLine("a %= 7; makes a = "+ a);
  }
}

The output of the above code will be:

a = 25
a += 5; makes a = 30
a -= 8; makes a = 22
a *= 4; makes a = 88
a /= 2; makes a = 44
a %= 7; makes a = 2

❮ C# - Operators