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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With