开发者

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 ?


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.


This is inherently impossible—value types cannot be null.

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


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);


If you are just assigning to object variable type, I suggest you just forget about using the method and just use conditional assignment

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜