technical notes

Tháng Ba 9, 2008

.NET 2.0 Cast operator vs. As operator

Chuyên mục: NET — ngduy @ 6:23 chiều

Khi chuyển từ untyped data values từ SQL database vào 1 biến, sẽ có tình huống xảy ra, khi cast từ DBNull sang một kiểu nào đó, ta sẽ bị InvalidCastException. Tuy nhiên, có một cách để gán thoải mái mà không lo lắng gì. Bắt đầu xem ví dụ dưới đây:

object objstr = DBNull.Value;
string str1 = objstr; //Cast throws an Exception
string str2 = objstr as string //No exception thrown and str2 == null

Có thể dùng as để viết code cho gọn như vd dưới:

if ( objstr == DBNull.Value )
{
    strResult = "Default";
}
else
{
    strResult = (string)objstr;
}
//Is equivalent to
strResult = objstr as string ?? "Default";

Như vậy, as operator giống như cast operator, nhưng khi gặp null value, as sẽ chuyển giá trị thành null chứ không thrown exception như là cast.

Tham khảo MSDN C# Programmer’s Reference tại http://msdn2.microsoft.com/en-us/library/cscsdfbt(vs.71).aspx thì được giải thích như sau:

expression <span class="kwrd">as</span> type</pre>
<pre><span class="rem">//is equivalent to</span></pre>
<pre>expression <span class="kwrd">is</span> type ? (type)expression : (type)null

No Comments Yet »

Chưa có phản hồi.

RSS các phản hồi của bài viết này. URL TrackBack

Để lại phản hồi

Blog at WordPress.com.