Unary and Binary Operators
Learn about unary and binary operators and explore their diverse capabilities for precision and manipulation.
Operators apply simple operations such as addition and multiplication to operands such as variables and literal values. They usually return a new value that is the result of the operation, and that can be assigned to a variable.
Binary operator
Most operators are binary, meaning that they work on two operands, as shown in the following pseudo-code:
var resultOfOperation = firstOperand operator secondOperand;
Example
Examples of binary operators include adding and multiplying, as shown in the following code:
int x = 5;int y = 3;int resultOfAdding = x + y;int resultOfMultiplying = x * y;
Unary operator
Some operators are unary, meaning they work on a single operand, and can apply before or after the operand, as shown in the following pseudocode:
var resultOfOperationAfter = onlyOperand operator;var resultOfOperationBefore = operator onlyOperand;
Example
Examples of unary operators include incrementors and retrieving a type or its size in bytes, as shown in the following code:
int x = 5;int postfixIncrement = x++;int prefixIncrement = ++x;Type theTypeOfAnInteger = typeof(int);string nameOfVariable = nameof(x);int howManyBytesInAnInteger = sizeof(int);
Ternary Operator
A ternary operator works on three operands, as shown in the following pseudocode:
var resultOfOperation = firstOperand firstOperatorsecondOperand secondOperator thirdOperand;
Exploring unary operators
Two common unary operators are used to increment, ++
, and decrement, --
, a ...