How to override the default value (int?), To get NULL instead of 0

I found a method here :

public static T GetValue<T>(object value)
{
    if (value == null || value == DBNull.Value)
        return default(T);
    else
        return (T)value;
}

How to rewrite it to get null if "value" is NULL?

+5
source share
5 answers

You do not need to rewrite it. You just need to call it like:

GetValue<int?>(value);
+10
source

int - value type not a reference type - it cannot matter null.

Use instead int?if the INT column in the database is NULL.

+5
source

null, "" NULL?

- int null. Nullable<int>. . , T == string. : .

public T? GetValue<T>(object value) where T : struct
{
    if (value == null || value == DBNull.Value)
        return null;
    else
        return (T?)value;
}

, terser:

public T? GetValue<T>(object value) where T : struct
{
    return (value == null value == DBNull.Value) ? null : (T?)value;
}

( T? Nullable<T>.)

+5

#, int , . :

int? thisValue;

null.

0

:

public T GetValue<T>(object value){
    if (value == null)
        return null;
    else if (value == DBNull.Value)
        return default(T);
    else
        return (T)value;
}
0

All Articles