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

I have an Oracle data table receiving columns that are null. So I think the code is nice and simple, what would I use? operand. AlternatePhoneNumber is a string in my C # model.

AlternatePhoneNumber = customer.AlternatePhoneNumber ?? ""

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

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

I know what error means, but why? cannot be used in DBNull? Are NULL and DBNull essentially the same?

Thank.

+3
source share
7 answers

The operator ??applies only to actual nulls.

nulland DBNull.Valuedo not match; DBNull.Valueis just a placeholder.

, AlternatePhoneNumber, ??. ( ).

customer - , column NullValue .

+15

null DBNull . System.DBNull - .

+3

, AlternatePhoneNumber . DBNull .

:

AlternatePhoneNumber = (customer.AlternatePhoneNumber as string) ?? ""
+3

DBNull - , ??. , :

string alternativePhoneNumber = DBNull.Value.Equals(customer) ? string.Empty : ((Customer)customer).AlternatePhoneNumber;
+2

:

public T IfNull<T>(object o, T value)
{
   return (o == DbNull.Value) ? value : (T)o;       
}
+2

, null , - , DBNull - , ADO.NET, , NULL ( DataTable).

() (?:), , :

AlternatePhoneNumber = customer.AlternatePhoneNumber is DBNull 
                           ? "" 
                           : customer.AlternatePhoneNumber;

:

static class NullExtensions
{
    public static T WhenNull<T>( this object value, T whenNullValue )
    {
        return (value == null || value is DBNull)
            ? whenNullValue
            : (T)value;
    }
}

, .

AlternatePhoneNumber = customer.AlternatePhoneNumber.WhenNull( "" );
+1

DBNull "".

"??" - , , "" .

+1

Source: https://habr.com/ru/post/1753888/


All Articles