Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about null strings and DBNull

I'm looking at some code for a .net program I'm working on. The previous author of the program gave the code to me over a year ago. Suddenly, I am seeing an exception thrown from code that I haven't touched:

if ((string)row["LevelName"] != "ABC")

The exception is "Unable to cast object of type 'System.DBNull' to type 'System.String'.

I thought that string was a nullable data type, so how can I possibly be getting this exception?

like image 848
Vivian River Avatar asked Nov 28 '22 03:11

Vivian River


1 Answers

I believe what you're looking for is:

if ((row["LevelName"] as String) != "ABC")

There is no implicit cast between DBNull and String.

It may have worked before because there just happened to be no NULLs in that column in your database. Maybe some data got corrupt, or someone changed a NOT NULL constraint on the table.

Basically if you explicitly cast something, you better make sure they have compatible dynamic types otherwise an exception is thrown. The as operator basically says "cast it to this if possible, otherwise the logical value is null." Obviously, the as operator only works on reference types since structs cannot be null.

like image 53
Mike Christensen Avatar answered Dec 05 '22 13:12

Mike Christensen