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

前端 未结 10 1298
滥情空心
滥情空心 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条回答
  • 2021-01-02 06:48
    new SqlParameter("@theParam", (object)theParam ?? DBNull.Value)
    
    0 讨论(0)
  • 2021-01-02 06:56

    The reason you can't use the null coalesce operator is that it has to return one type and you are providing more than one type. theParam is a string. DbNull.Value is a reference to a static instance of type System.DbNull. This is what its implementation looks like;

    public static readonly DBNull Value = new DBNull(); 
    //the instantiation is actually in the 
    //static constructor but that isn't important for this example
    

    So if you were to have a NullCoalesce method, what would its return type be? It can't be both System.String and System.DbNull, it has to be one or the other, or a common parent type.

    So that leads to this type of code;

    cmd.Parameters.Add(
        new SqlParameter("@theParam", (object)theParam ?? (object)DBNull.Value)
    );
    
    0 讨论(0)
  • 2021-01-02 06:59

    I'm pretty sure that just passing a null to the SqlParameter constructor results in it being sent as a DBNull.Value... I may be mistaken, since I use the EnterpriseLibraries for DB access, but I'm quite sure that sending a null is fine there.

    0 讨论(0)
  • 2021-01-02 06:59

    Use this syntax:

    (theParam as object) ?? (DBNull.Value as object)

    In this case both parts of operator ?? are of the same type.

    0 讨论(0)
提交回复
热议问题