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?
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 anull
value if one or both operands arenull
(an exception being the&
and|
operators of thebool?
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.