[C#] How to fix "object reference not set to an instance of an object"

No comments
Oh! No...
When you coding with .Net. Many time you meet an error: "object reference not set to an instance of an object".
What happen???

Example 1: Convert null to int
string query = "Select * from USERS where ID = '" + txtUID.Text + "'";
SqlCommand cmd = new SqlCommand(query , CN);
int count = (int)cmd.ExecuteScalar();//Error here
What problem? ExecuteScalar return to null when record not found in database. In case, you can using Convert class
Convert.ToInt32(cmd.ExecuteScalar());//It will return 0 when ExecuteScalar() return null
Example 2: Try get object properties when this object is null
var str= null;
if(str!="")// Error here
{
//do some thing
}
Resolve the problem: You can try
var str= null;
if(str !=null && str!="")// Error here
{
//do some thing
}
Or try this
var str= null;
if(!String.IsNullOrEmpty(str))// Error here
{
//do some thing
}
Example: Very much error!
// About 10000 lines
Resole all with
try{
//All code here
}
catch (NullReferenceException ex)
        {
            ShowMessageBox("Error" + ex.Message);
        }

No comments :

Post a Comment