Null-Coallescing Operator - Why Casting?

牧云@^-^@ 提交于 2020-01-24 05:38:05

问题


Can anyone please tell me why does the first of the following statements throws a compilation error and the second one does not?

NewDatabase.AddInParameter(NewCommand, "@SomeString", DbType.String, SomeString ?? DBNull.Value); // <-- Throws compilation error!
NewDatabase.AddInParameter(NewCommand, "@SomeString", DbType.String, (object)(SomeString) ?? DBNull.Value); // <-- Compiles!

I tried other nullable types such as byte? and got the same result. Can anyone please tell me why do I need to cast to object first?


回答1:


You need to tell the compiler what type to use. The result type of the null coalescing operator has to be the same as one of the operand types (or the underlying type of the first operand, if it's a nullable value type, in some cases). It doesn't try to find a "most specific type which both operands can be converted to" or anything like that.

For the details of how the language is defined when it comes to the null coalescing operator, see the C# 4 language specification, section 7.13:

The type of the expression a ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type, or A otherwise.




回答2:


The first example fails because SomeString and DBValue.Null are not implicitly interchangable types.




回答3:


That is because the type on the right-hand side of the null-coalescing operator must be implicitly convertible to the type on the left hand side (or vice versa). For your first example, the types involved are string and DBNull. These types are unrelated, so conversion fails.




回答4:


DBValue.Null is not a string; it's an Object. .NET will not implicitly cast to Object in expressions; it must be explicitly told that you are expecting an Object result.




回答5:


Because the expression needs to have a single return type. Since String and DbValue can't be cast to one another, the compiler can't figure out which type return do you want. When you cast to Object, you're giving the compiler a type it can cast to.



来源:https://stackoverflow.com/questions/6333216/null-coallescing-operator-why-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!