Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override default(int?) to obtain NULL instead 0

Tags:

c#

null

I found here the method:

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 obtain null if "value" is NULL?

like image 951
Max Kilovatiy Avatar asked Jun 07 '11 12:06

Max Kilovatiy


People also ask

How do I assign an int to null?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Is null an int 0?

NULL typically is an integer constant 0 or (void*)0 or the like. It may have a different implementation or type - It could be ((int*) 0xDEADBEEF) as strange as that may be. NULL might be type int . It might be type void * or something else.

Can you pass null as an int?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

What happens if you cast null to int?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.


1 Answers

You don't need to rewrite it. You just need to call it as:

GetValue<int?>(value);
like image 94
Phil Degenhardt Avatar answered Oct 04 '22 16:10

Phil Degenhardt