Max Kilovatiy
Max Kilovatiy

Reputation: 798

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

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?

Upvotes: 5

Views: 7519

Answers (5)

Barry Kaye
Barry Kaye

Reputation: 7761

Do you mean this:

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

Upvotes: 0

Jakub Konecki
Jakub Konecki

Reputation: 46008

int is a value type not a reference type - it cannot have a value of null.

Consider using int? instead if your INT column in the database is nullable.

Upvotes: 5

Phil Degenhardt
Phil Degenhardt

Reputation: 7264

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

GetValue<int?>(value);

Upvotes: 11

IKEA Riot
IKEA Riot

Reputation: 111

In C#, an int is a value type and therefore cannot be null as Jakub said. However, you can define a variable :

int? thisValue;

This can be set to null.

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 545558

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

You can’t – int cannot be null. You can, however, use Nullable<int> instead. But this only works for value types. For instance, it won’t work any more for T == string. In order to accomplish this you will need to write two distinct functions, one for nullable value types and one for reference types.

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

Or, terser:

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

(In all cases, T? is a shortcut for Nullable<T>.)

Upvotes: 5

Related Questions