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

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 from marking it as an invalid operation? Should I follow custom exception handling?

+4
source share
4 answers

This is null .

C # 3.0 Language Specification (Section ยง7.2.7: Raised Operators)

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

there is a removed form of the operator if the operand and result types are all value types that do not allow null values. Is a raised form built by adding a single modifier ? to each operand and type of result. The raised statement creates a null value if one or both operands is null (the exceptions are the & and | operators of type bool? , as described in ยง7.10 0,3). Otherwise, the captured statement expands the operands, applies the main statement, and completes the result.


How can I prevent the compiler from marking it as an invalid operation? Should I follow custom exception handling?

This is not an invalid operation. It will not throw an exception, so you do not need to handle exceptions in this case.

+19
source

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

 int v2 = 5 * v1.Value; 

This will throw a runtime exception if v1 is null.

+11
source

Its value will be "zero", in this context, at least, we can assume that it coincides with the zero value of the database, that is, instead of "Nothing" or "Zero", it means "Unknown". Five episodes of the Unknown are still unknown, it will also never be an "empty string", since you are dealing with numbers, not strings.

I'm not sure what you mean by "How can I prevent the compiler from marking it as an invalid operation?" since this code compiles and works fine for me in Visual Studio 2008 =)

+1
source

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

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

or

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

All Articles