Assignment Operators ใช้กำหนดค่าให้ตัวแปร รวมถึง Compound Assignment (คำนวณและกำหนดพร้อมกัน)
ตาราง Assignment Operators
| Operator | ชื่อ | ตัวอย่าง | เทียบเท่า |
|---|---|---|---|
| = | Simple Assignment | c = a + b | c = a + b |
| += | Add AND Assign | c += a | c = c + a |
| -= | Subtract AND Assign | c -= a | c = c - a |
| *= | Multiply AND Assign | c *= a | c = c * a |
| /= | Divide AND Assign | c /= a | c = c / a |
| %= | Modulus AND Assign | c %= a | c = c % a |
| <<= | Left Shift AND Assign | c <<= 2 | c = c << 2 |
| >>= | Right Shift AND Assign | c >>= 2 | c = c >> 2 |
| &= | Bitwise AND Assign | c &= 2 | c = c & 2 |
| ^= | Bitwise XOR Assign | c ^= 2 | c = c ^ 2 |
| |= | Bitwise OR Assign | c |= 2 | c = c | 2 |
ตัวอย่างโค้ด
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int c;
c = a;
Console.WriteLine("= : {0}", c); // 21
c += a;
Console.WriteLine("+= : {0}", c); // 42
c -= a;
Console.WriteLine("-= : {0}", c); // 21
c *= a;
Console.WriteLine("*= : {0}", c); // 441
c /= a;
Console.WriteLine("/= : {0}", c); // 21
c = 200;
c %= a;
Console.WriteLine("%= : {0}", c); // 11 (200 % 21)
c <<= 2;
Console.WriteLine("<<= : {0}", c); // 44 (11 * 4)
Console.ReadLine();
}
}
}
ผลลัพธ์
= : 21 += : 42 -= : 21 *= : 441 /= : 21 %= : 11 <<= : 44
หมายเหตุ
- Compound Assignment ประหยัดการเขียนโค้ดและอ่านง่ายกว่า
- สำหรับ Event:
event += Handler,event -= Handler - Nullable Types รองรับ:
int? x = null; x += 5;(x ยังคงเป็น null)