Web Hosting Talk







View Full Version : Basic C# Question


FW-Mike
06-09-2005, 12:22 PM
You guys always seem to help me out, so here goes another question.

Preface: I am working on a sync between Quickbooks and the Web. The below code is in a loop and is meant to prepare variables for sync. Here is the pertaining snippet of code:


string Name = customerRet.Name.GetValue();
string CompanyName = customerRet.CompanyName.GetValue();
string Salutation = customerRet.Salutation.GetValue();


The error I get when executing the code is:

Additional information: Object reference not set to an instance of an object.


Regarding the `string Salutation` line. I know why it is doing this, there is no salutation in the given row.

The problem is that I cannot think of a proper way to check to see if it exists and only proceed if so. I cannot use IsEmpty() -- same error.

What should I do here?

unlucky1
06-09-2005, 02:28 PM
string Salutation;
try
{
Salutation = customerRet.Salutation.GetValue();
}
catch
{
Salutation = string.Empty();
}

That would be one way.

banner
06-09-2005, 11:37 PM
A better option would be to do:

string Salutation = string.Empty;
if(customerRet.Salutation != null)
{
Salutation = customerRet.Salutation.GetValue();
}


I'm not a fan of "hiding" exceptions like unlucky1's code will do. While it'll get rid of this error, it could also hide more important (or fatal) exceptions that you do want to see.

-T{H}R-
06-10-2005, 06:44 AM
Plus if you can use a simple if statement rather than a catch try you should.