[VB.NET] Behavior when writing a Nullable type with a one-liner If

1 minute read

Returns Nothing with Nullable type on the left side and one-liner If on the right side

Such a source
Since it is an example, the text remains Nothing, and the return value when it is not Nothing is appropriately set to 100.

NullableIfSample.vb


'Explicitly initialize for clarity.
Dim text As String = Nothing
Dim value As Integer? = If(text Is Nothing, Nothing, 100)

You want the return value to be Nothing or some other value (100 in the example above).
Well, it’s rare, but there are occasional cases where you want to do something like this.

You can write it gently in If-Else, but it’s a waste of lines and it doesn’t look good, so I just want to write it in one liner.

what will happen

If it is not Nothing, it is fine, and if it is ** Nothing, 0 ** is returned.
You can see why by writing the same code in C #.

NullableIfSample.cs


string text = null;
int? value = text == null ? default(int) : 100;
//I can't write this.
// int? value = text == null ? null : 100;

Nothing has the function of default in C #, so it will be 0, which is the initial value of Integer. In the case of C #, it is a problem that does not occur because it can not be written that null is returned when it is null like VB.NET, but it may be good to remember.

How to write

There is no choice but to give up writing with one liner.

NullableIfSample.vb


Dim value As Integer?

If text Is Nothing Then
    value = Nothing
Else
    value = 100
End If

Well, the number of lines has increased and it doesn’t look good. .. ..

By the way, the code written in one liner is explicitly typed without type inference, but if you try to type infer, it will be a normal int type, so be careful.

Afterword

I’ve been thinking about writing something for a long time, and I sometimes submit a report using Qiita in another case, so I’d like to get used to writing a little story …
(Because I don’t have such a big technical ability …)