C# - TPL2141 logo C# - TPL2141

An arithmetic expression is an expression built up using

  1. numbers
  2. arithmetic operators (such as +, -, *, /), and
  3. parentheses

(Wagner, 2001)

Arithmetic operators

In C#, the primary arithmetic operators are:

Operators Description
- (unary) Negation
* Multiplication
/ Division
+ Addition
- Subtraction
% Modulo

(Techotopia, 2016)

Here is a simple example demonstrating some of the operators:

Console.WriteLine(1 + 2);   // 3
Console.WriteLine(1 - -2);  // 3
Console.WriteLine(1 * 2);   // 2
Console.WriteLine(1 / 2);   // 0
Console.WriteLine(1 / 2.0); // 0.5
Console.WriteLine(5 % 3);   // 2

Live-code example

Mixed mode arithmetic operations

In C#, an arithmetic expression can contain operands of different integral type. However, the resulting type will often be the larger integral type (widening assignment coercions). For example,

int a = 1;
double b = 1.2;

var result = a + b;
Console.WriteLine(result.GetType());

The output will be

System.Double

Live-code example

References

  1. Wagner, E. G. (2001, October 23). Arithmetic Expressions. Retrieved from https://www.ii.uib.no/ wagner/hsalg/arithexp.htm
  2. Techotopia. (2016, October 27). C Sharp Operators and Expressions. Retrieved from https://www.techotopia.com/index.php/C_Sharp_Operators_and_Expressions