What is the equivalent of VB.NET default C # keyword?

Possible duplicate:
Error? If you assign an integer with a null value through a ternary operator, it cannot become null

Although this question may seem to be a duplicate of many, it is actually asked for a specific reason. Take this code, for example:

Dim n As Integer? = If(True, Nothing, 1)

In this code, the ternary expression should return Nothing, but it sets n to 0. If it were C #, I could say default(int?)it and it will work fine. Now it looks like I have to pull out a triple and use a regular If block, but I really want to use a triple.

If nothing was really equivalent to VB.NET for C # by default, how can you explain this behavior?

+5
source share
1 answer

VB.NET , the equivalent of C # default, is a keyword Nothing. The code you wrote should compile just fine, as long as it Id.Valuereturns a value Integer.

The reason your updated sample is wrong is due to nature Nothing. In VB.NET, it Nothingis an empty value and it is converted to any type. Now, for the expression, the Ifcompiler must determine what the type of the return value should be, and he does this by considering the two arguments of the value.

Nothing , 1 Integer. Nothing Integer, Integer. , Nothing , Integer, Integer?.

- , , 1 Integer?.

Dim n As Integer? = If(True, Nothing, CType(1, Integer?))
+6

All Articles