Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

Why can't you cast DBNull to string?

It's been really bugging me. It would help if there were a good reason.

Colm
Monday, February 14, 2005

I'd imagine it's because null represents the absence of any value so you can't cast nothing to something.

You might be able to try:

string myString = objectThatIsDBNull + string.Empty;

It worked in VB6!

smallbiz
Monday, February 14, 2005

Nice fix!

Colm
Monday, February 14, 2005

Probably because an empty string and Null are different values in SQL Server.  If you do:

INSERT INTO Table(field) VALUES(NULL)
INSERT INTO Table(field) VALUES('')

SELECT COUNT(*) FROM TABLE WHERE field IS NULL

you'd get 1 back.

And yes, it bugs the hell out of me.

Grant
Monday, February 14, 2005

"Why can't you cast DBNull to string?" - because it isn't a string. But it does have a ToString() method that returns an empty string.

Duncan Smart
Monday, February 21, 2005

>"Why can't you cast DBNull to string?" - because it isn't a string.

That's kinda the point of casting it.

Colm O'Connor
Tuesday, February 22, 2005

Sorry, but "cast" does not mean "convert." ... I'm not being pedantic - you've got your terminology wrong. It'll really help to understand the difference.

Duncan Smart
Monday, February 28, 2005

Just write a series of DB value interface functions, that return the type you want if it is a null.

And these default to empty string or zero, or you can pass in a different value if necessary.

Murg
Tuesday, March 01, 2005

I am stuck.  I have a datagrid with a dropdown. I have coded it to work with Edit - Delete.  But when I try to do an Add - I must throw a Clone of the DataSet (DataTable) back at the ASP DropDown and it throws an error since the DataTextField and DataValueField are strings and can not accept DbNull.

Any work arounds?

NHJim
Friday, April 08, 2005

*  Recent Topics

*  Fog Creek Home