Search code examples
c#oracle-databasedbnull

Why can't I use '??' operand for System.DBNull value?


I have an Oracle data table fetching columns that be null. So I figure to keep the code nice and simple that I'd use the ?? operand. AlternatePhoneNumber is a string in my C# model.

AlternatePhoneNumber = customer.AlternatePhoneNumber ?? ""

However, even with that code I still get the error.

System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.

I know what the error means but why is ?? not usable on DBNull? Isn't null and DBNull essentially the same?

Thank you.


Solution

  • The ?? operator only applies to actual nulls.

    null and DBNull.Value are not the same; DBNull.Value is simply a placeholder object.

    Also, that exception is coming from inside the AlternatePhoneNumber property, before your ?? operator executes. (Your code doesn't have a cast).

    If customer is a row in a typed dataset, change the column's NullValue property in the designer.