Handling string and null value?

N

___Newbie___

Hello,
Why can't a string handle null values? Do I really need to check with
IsDBNull() for null values?

e.g.

fieldName = reader.GetString(0);
if (!reader.IsDBNull(1))
{
fieldNationality = reader.GetString(1); // Exception here! for null
value
} else {
fieldNationality = "";
}
uxPersonList.Items.Add(fieldName + " " + fieldNationality);

Thanks.
 
J

jg

I know for sure you can not compare string to the c# keyword null directly
string strtest = null;
string strnull = null;

// can't use if ( stttest is Null )
// but you can
if (strtest is strnull)
{
system.console.writeline("null");
};

as for your original question,, the problem is not null in string for your
code but your object reader.
When your object or class reader is null, you have not instantiated treader
so, nothing works for reader.
 
N

___Newbie___

Thanks.
In short, null in string is different from null in database. It seems so
strange. Is it possible to create a custom datatype based on string to
actually handle real null value? Or the reader.GetString() even can't handle
null values. Is there any alternative?
 
C

Cor Ligthert [MVP]

Hi,

You can handle binary nulls 00, however the IDE breaks those when a string
is displayed with that.

I hope this helps,

Cor
 
S

Scott Roberts

___Newbie___ said:
Hello,
Why can't a string handle null values?

Because a "null" is not of type "string".
Do I really need to check with
IsDBNull() for null values?

Yes. And rightfully so (IMO, of course).

Perhaps in your application a "null" and the "empty string" are logically
equivalent, but that's not the case for every application that can be
written with C#.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top