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.
The
??operator only applies to actualnulls.nullandDBNull.Valueare not the same;DBNull.Valueis simply a placeholder object.Also, that exception is coming from inside the
AlternatePhoneNumberproperty, before your??operator executes. (Your code doesn’t have a cast).If
customeris a row in a typed dataset, change the column’sNullValueproperty in the designer.