ตัวแปร (Variables)
ตัวแปรคือชื่อที่อ้างอิงพื้นที่หน่วยความจำ แต่ละตัวแปรมี Type กำหนดขนาด Layout ช่วงค่า และ Operation ที่ทำได้
ประเภทข้อมูลใน C# (Type System)
แบ่งเป็น 3 หมวดหลัก:
1. Value Types (ประเภทค่า)
- เก็บค่าโดยตรง (Directly contain data)
- สืบทอดจาก
System.ValueType - เก็บใน Stack (โดยทั่วไป)
- ตัวอย่าง:
int, double, bool, char, struct, enum - Assignment = Copy ค่า (Deep copy)
2. Reference Types (ประเภทอ้างอิง)
- เก็บ Reference (Address) ไปยัง Object บน Heap
- หลายตัวแปรอาจชี้ Object เดียวกัน — เปลี่ยนผ่านตัวหนึ่ง ส่งผลต่ออีกตัว
- ตัวอย่าง Built-in:
object, string, dynamic, delegate, interface, array, class - Default value =
null
3. Pointer Types (ประเภท Pointer) — Unsafe Context
- เก็บ Memory Address โดยตรง
- ใช้ใน
unsafeContext เท่านั้น - ตัวอย่าง:
int* p = &x; - ใช้สำหรับ Interop, High-performance, Low-level
ตัวดำเนินการ (Operators)
สัญลักษณ์บอก Compiler ให้ทำ Mathematical/Logical Manipulation
หมวดหมู่หลัก
| หมวด | ตัวดำเนินการ | ตัวอย่าง |
|---|---|---|
| Arithmetic | + - * / % ++ -- | a + b, i++ |
| Relational | == != < > <= >= | x == y, a > b |
| Logical | && || ! ^ | a && b, !flag |
| Bitwise | & | ^ ~ << >> | flags & Mask, x << 2 |
| Assignment | = += -= *= /= %= &= ^= |= <<= >>= | x += 5 |
| Null-related | ?? ??= ?. ?[] | x ?? default, obj?.Prop |
| Type-related | is as typeof sizeof nameof | obj is string, typeof(int) |
| Other | ?: ??= => (lambda) () (cast) new | cond ? a : b, x => x*2 |
Operator Precedence (ลำดับความสำคัญ) — สรุปสำคัญ
- Primary:
x.y, f(x), a[x], x++, x--, new, typeof, checked, unchecked - Unary:
+, -, !, ~, ++x, --x, (T)x, await - Multiplicative:
*, /, % - Additive:
+, - - Shift:
<<, >> - Relational/Type:
<, >, <=, >=, is, as - Equality:
==, != - Bitwise AND:
& - Bitwise XOR:
^ - Bitwise OR:
| - Conditional AND:
&& - Conditional OR:
|| - Null-coalescing:
?? - Conditional:
?: - Assignment:
=, +=, -=, ... - Lambda:
=>
ตัวอย่างการประกาศตัวแปร
// Value Types
int number = 42;
double price = 19.99;
bool isActive = true;
char grade = 'A';
Point p = new Point(10, 20); // Struct
// Reference Types
string name = "John";
int[] numbers = { 1, 2, 3 };
List items = new List();
object obj = new object();
dynamic dyn = "anything";