An arithmetic expression is an expression built up using
- numbers
- arithmetic operators (such as
+
,-
,*
,/
), and - parentheses
Arithmetic operators
In C#, the primary arithmetic operators are:
Operators | Description |
---|---|
- (unary) | Negation |
* | Multiplication |
/ | Division |
+ | Addition |
- | Subtraction |
% | Modulo |
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
- Wagner, E. G. (2001, October 23). Arithmetic Expressions. Retrieved from https://www.ii.uib.no/ wagner/hsalg/arithexp.htm
- Techotopia. (2016, October 27). C Sharp Operators and Expressions. Retrieved from https://www.techotopia.com/index.php/C_Sharp_Operators_and_Expressions