var คือ Implicitly Typed Local Variable - ให้ Compiler สรุป Type จากค่าที่ Assign (Compile-time Type Inference)
ตัวอย่างพื้นฐาน
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
var myInt = 5; // int
var myString = "Amit"; // string
var myDouble = 3.14; // double
var myBool = true; // bool
Console.WriteLine($"Int: {myInt}, String: {myString}, Double: {myDouble}, Bool: {myBool}");
}
}
}
ผลลัพธ์
Int: 5, String: Amit, Double: 3.14, Bool: True
ใช้กับ Array
var numbers = new int[] { 65, 43, 88, 56 }; // int[]
var names = new[] { "A", "B", "C" }; // string[]
foreach (var n in numbers) Console.WriteLine(n);
ใช้กับ Anonymous Types (สำคัญ)
var person = new { Name = "John", Age = 30 };
Console.WriteLine(person.Name); // John
// person.Name = "Jane"; // Error - Anonymous Types เป็น Immutable
กฎการใช้ var
- ต้อง Initialize ค่าทันที (
var x;❌) - ไม่สามารถเป็น null ได้โดยตรง (
var x = null;❌) - ใช้ได้เฉพาะ Local Variables (ใน Method) ไม่ใช่ Fields/Properties
- Type ถูกกำหนดที่ Compile-time - ไม่ใช่ Dynamic
Best Practices
- ใช้เมื่อ Type ชัดเจนจากขวา Assignment:
var list = new List<string>();✅ - หลีกเลี่ยงเมื่อ Type ไม่อvious:
var result = GetData();❌ (ควรระบุ Type ชัดเจน) - Anonymous Types ต้องใช้ var (ไม่มีชื่อ Type)