Unary Operators ทำงานกับ Operand เพียงตัวเดียว
รายการ Unary Operators
| Operator | ชื่อ | ตัวอย่าง |
|---|---|---|
| + | Unary Plus | +5 (ไม่มีผล) |
| - | Unary Minus (Negation) | -5 |
| ! | Logical NOT | !true → false |
| ~ | Bitwise Complement | ~5 → -6 |
| ++ | Increment (Prefix/Postfix) | ++a, a++ |
| -- | Decrement (Prefix/Postfix) | --a, a-- |
| (type) | Cast | (int)3.14 |
| * | Pointer Dereference | *ptr (unsafe context) |
| & | Address-of | &x (unsafe context) |
| sizeof | Size of Type | sizeof(int) → 4 |
ตัวอย่าง sizeof Operator
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int)); // 4
Console.WriteLine("Size of char: {0}", sizeof(char)); // 2
Console.WriteLine("Size of short: {0}", sizeof(short)); // 2
Console.WriteLine("Size of long: {0}", sizeof(long)); // 8
Console.WriteLine("Size of double: {0}", sizeof(double)); // 8
Console.WriteLine("Size of float: {0}", sizeof(float)); // 4
Console.WriteLine("Size of bool: {0}", sizeof(bool)); // 1
Console.WriteLine("Size of decimal:{0}", sizeof(decimal)); // 16
Console.ReadLine();
}
}
}
ผลลัพธ์
Size of int: 4 Size of char: 2 Size of short: 2 Size of long: 8 Size of double: 8 Size of float: 4 Size of bool: 1 Size of decimal: 16
Bitwise Complement (~) ตัวอย่าง
int a = 5; // Binary: 0000 0101 int b = ~a; // Binary: 1111 1010 = -6 (Two's Complement)
Logical NOT (!) ตัวอย่าง
bool flag = true; bool notFlag = !flag; // false