Unary operations are operations that only operate on a single operand. C# provides several unary operators that you can use to perform various operations on a single value. These operators are applied to a single operand to produce a new value.
The following are the unary operators available in C#:
- Unary plus operator (+)
- Unary negation operator (-)
- Increment operator (++)
- Decrement operator (–)
- Logical negation operator (!)
- Bitwise complement operator (~)
- Dereference operator (*)
- Address-of operator (&)
- Type-of operator (typeof)
In this tutorial, we will go through each of these unary operators and explain how to use them.
Unary plus operator (+)
The unary plus operator (+) is used to indicate a positive value. It is usually unnecessary because positive numbers are already indicated by default.
Example:
int x = 10;
int y = +x; // y is also 10
Unary negation operator (-)
The unary negation operator (-) is used to negate a value, making it negative.
Example:
int x = 10;
int y = -x; // y is -10
Increment operator (++)
The increment operator (++) is used to increase the value of a variable by one.
Example:
int x = 10;
x++; // x is now 11
Decrement operator (–)
The decrement operator (–) is used to decrease the value of a variable by one.
Example:
int x = 10;
x--; // x is now 9
Logical negation operator (!)
The logical negation operator (!) is used to reverse the logical state of a boolean value. It converts true to false, and false to true.
Example:
bool x = true;
bool y = !x; // y is false
Bitwise complement operator (~)
The bitwise complement operator (~) is used to invert all the bits of an integer.
Example:
int x = 10; // binary: 1010
int y = ~x; // binary: 0101, y is -11 in decimal
Dereference operator (*)
The dereference operator (*) is used to access the value that a pointer is pointing to.
Example:
int x = 10;
int* ptr = &x;
int y = *ptr; // y is also 10
Address-of operator (&)
The address-of operator (&) is used to get the memory address of a variable.
Example:
int x = 10;
int* ptr = &x; // ptr points to the memory address of x
Type-of operator (typeof)
The typeof operator (typeof) is used to get the System.Type object for a type.
Example:
Type t = typeof(int); // t is the System.Type object for the int type
Conclusion
That’s it! We’ve covered all the unary operators in C#. I hope this tutorial has been helpful in understanding unary operations in C#. If you have any questions or comments, feel free to leave them below.