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

前端 未结 10 1370
滥情空心
滥情空心 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: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)
    );
    

提交回复
热议问题