Is it possible to coalesce string and DBNull in C#?

前端 未结 10 1371
滥情空心
滥情空心 2021-01-02 06:24

I\'m writing a C# routine to call a stored proc. In the parameter list I\'m passing in, it is possible that one of the values can legally be null. So I thought I\'d use a

10条回答
  •  萌比男神i
    2021-01-02 06:32

    Not like that, no. The types have to match. The same is true for the ternary.

    Now, by "match", I don't mean they have to be the same. But they do have to be assignment compatible. Basically: in the same inheritance tree.

    One way to get around this is to cast your string to object:

    var result = (object)stringVar ?? DBNull.Value;
    

    But I don't like this, because it means you're relying more on the SqlParameter constructor to get your types right. Instead, I like to do it like this:

    cmd.Parameters.Add("@theParam", SqlDbTypes.VarChar, 50).Value = theParam;
    // ... assign other parameters as well, don't worry about nulls yet
    
    // all parameters assigned: check for any nulls
    foreach (var p in cmd.Parameters) 
    { 
        if (p.Value == null) p.Value = DBNull.Value; 
    }
    

    Note also that I explicitly declared the parameter type.

提交回复
热议问题