Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

Okay, I am really tired just one last post. Consider that you have a database with fields FirstName and Amount. Amount is an integer field. For some amount you did not enter anything and hence they are default to null. When you run the loop below:

 int amount = 0;
            
string firstName = null;

            
foreach (DataRow row in ds.Tables[0].Rows)
            {
                firstName = row["FirstName"] 
as String;
                amount = (
int) row["Amount"]; // Error converting null to int 
               
             
            
}

Although we can avoid this error by simply doing:

int amount = 0;
            
string firstName = null;

            
foreach (DataRow row in ds.Tables[0].Rows)
            {
                firstName = row["FirstName"] 
as String;

                
if (row["Amount"] == DBNull.Value)
                { }
                
else {
                    amount = (
int)row["Amount"];  
                }
               
             
            }

Now in 2.0 we have nullable types so we can do something like this:

  int? amount = null;
            
string firstName = null;

            
foreach (DataRow row in ds.Tables[0].Rows)
            {
                firstName = row["FirstName"] 
as String;

                amount = row["Amount"] 
as int?;               
             
            }

The above code will not through any exception. Offcourse if you try to print it using amount.Value it will cause the exception to be thrown.

powered by IMHO

 

Posted on Thursday, November 10, 2005 10:44 PM | Back to top


Comments on this post: Nullable Types in .NET 2.0

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net