简体   繁体   中英

C# : return dbnull.value or system.type from function?

I want to create a function (c#):

int PutInt (int? x)
{
    if (x.HasValue)
        return x.Value;
    else
        return DBNull.Value;
}

but there is no cast from int to DBNull.Value. Is there any way to create such a function ?

This is inherently impossible—value types cannot be null.

You need to use a nullable type ( int? ), which makes your function utterly useless.

Lets assume your DBMS is SQLServer, you can transform your function to

object PutInt (int? x)
{
    if (x.HasValue)
        return (object)x.Value;
    else
        return (object)DBNull.Value;
}

Because SQLParamater Value property assumes type object. Hope I answer your question.

No, you can't cast int to DBNull.Value . This is used to evaluate the contents of database fields, not of nullable types. The value of a nullable type would simply be null .

A better option than the function that you've defined is to use the null coalescing operator ( ?? ).

It has very similar logic to that which you've attempted to construct in your function. Consider the following lines of code:

// Declare a nullable int, and set it to null
int? x = null;

// Assign int y to x, unless x is null, in which case, set y = -1
int y = x ?? -1;

// The variable y now has a value of -1
Console.WriteLine(y);

如果您只是分配给对象变量类型,建议您不要使用方法,而只使用条件分配

 object obj = (x.HasValue? x.Value : DBNull.Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM