Nullable Type
posted on 20 Dec 2004 11:09 by tidno1 in csharp-and-dotnetปัญหาหนึ่งเวลาทำงานกับ database ก็คือเราจะต้องมา handle field ที่อาจจะเป็น null ซึ่งอาจจะเกิดจากความผิดของ dba หรือจะเกิดจากอะไรก็ตามที
หรือในอีกกรณีที่อ่านมาจาก querystring ของ asp.net การที่ .net ไม่มี container type อย่าง Integer หรือ Character แบบที่ java มี ทำให้การ box/unbox จะเขียนแล้วดูไม่สวยเหมือนอย่างทางฝั่ง java
C# 2.0 จึงได้เพิ่ม Nullable Types
ตัวอย่างการใช้
int? x;
if (x != null) // or x.HasValue
Console.WriteLine(x.Value);
else
Console.WriteLine("Undefined");
โดย nullable type จะเก็บค่าได้สองชนิดคือ type เดิมของมัน และค่า null
Syntax
ใช้ได้สองวิธีคือ(update)
System.Nullable<T>
T? var;
โดย T เป็น value type ใด ๆ
int? i = 10;
Nullable<int> a= 5;
double? x = 3.14;
bool? flag = null;
char? letter = 'a';
int?[] MyArray = new int?[10];
Member
-HasValue เป็น false เมื่อ เป็น null
-Value ถ้า HasValue เป็น true Value จะเก็บค่าของตัวแปรนั้น ถ้า HasValue เป็น false แล้วเราพยายามจะ access ตัวแปรนั้น จะเกิด System.InvalidOperationException ขึ้น
Conversion
- explicit conversions
int? x = null;
int y = x; // Won't compile
int y = (int)x; // Compiles, but will create an exception if x is null
int y = x.Value; // Compiles, but will create an exception if x is null - implicit conversions
อันนี้ตัวอย่างใน help เขียนไว้ ต๊อง ๆ อะครับ <>
int x = 0;
int? y = x + 10; // Implicit conversion
Operators
ถ้า operand อย่างน้อยหนึ่งตัวเป็น null, expression นั้นจะ evaluate ได้ค่า null ออกมา นอกจากนั้น จะคิดค่าตามปกติ
boolean expression ก็เช่นกัน ถ้าตัวใดตัวหนึ่งเป็น null, expression นั้นจะ evaluate ได้ค่า false
The ?? Operator
ใช้กำหนดค่า default เมื่อเรา assign ค่า nullable type ให้กับ non-nullable type
ex:
int? x = null;
int y = x ?? -1; // y = x != null ? x : -1;
หรืออาจใช้กับกับ nullable type หลาย ๆ ตัวก็ได้
int? x;
int? y;
//...
int? z = x ?? y; // If x is not null, z = x. If x is null, x = y
The bool? type
bool? type ก็เหมือนกับ boolean type ของ SQL นั่นคือมีสามค่า true, false และ null boolean operation จะให้ผลดังนี้
and (true and null) = null, (false and unknown) = false, (null and null) = null
or (true or null) true, (false or null) = null, (null or null) = null
edit @ 2005/04/08 11:50:00
edit @ 2005/05/19 09:37:56

#1 By ลิ่ว on 2004-12-20 11:55