System.Nullable<T> What is the value of null * int value?

送分小仙女□ 提交于 2020-01-14 12:40:58

问题


Consider the following statements:

int? v1 = null;

int? v2 = 5 * v1;

What is the value of v2? (null or empty string?)

How can I prevent the compiler to mark it as invalid operation? Do I need to follow custom exception handling?


回答1:


It's null.

C# Language Specification 3.0 (Section §7.2.7: Lifted operators)

For the binary operators + - * / % & | ^ << >> :

a lifted form of an operator exists if the operand and result types are all non-nullable value types. The lifted form is constructed by adding a single ? modifier to each operand and result type. The lifted operator produces a null value if one or both operands are null (an exception being the & and | operators of the bool? type, as described in §7.10.3). Otherwise, the lifted operator unwraps the operands, applies the underlying operator, and wraps the result.


How can I prevent the compiler to mark it as invalid operation? Do I need to follow custom exception handling?

It's not an invalid operation. It won't throw an exception so you don't need to handle exceptions in this case.




回答2:


If you want the operation to be prevented by the compiler, make the second variable non-nullable. Then you will be forced to write:

int v2 = 5 * v1.Value;

This will throw an exception at run time if v1 is null.




回答3:


Its value will be "null", in this context at least can be considered to be the same as a database null, i.e. rather than Nothing, or Zero, it means "Unknown". Five lots of Unknown is still Unknown, it'll also never be "empty string" as you're dealing with numbers, not strings.

I'm not sure what you mean by "How can I prevent the compiler to mark it as invalid operation?" as this code compiles and runs fine for me under Visual Studio 2008 =)




回答4:


I'm not sure what you are trying to do, but if you want v2 to be null if v1 is null then you should test if v1 has a value prior to using it.

int? v2 = v1.HasValue ? 5 * v1.Value : null;

or

int? v2 = null;
if (v1.HasValue) { v2 = 5 * v1.Value; }


来源:https://stackoverflow.com/questions/1327917/system-nullablet-what-is-the-value-of-null-int-value

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