If operator in VB casts Nothing to type-default instead of nullable of that type

vbnet
sonarqube

(Thorsteinn) #1

When the If(arg1, arg2, arg3) operator in VB (see MSDN) has Nothing for argument 2 or 3, then if the other argument is not a nullable type, the compiler converts Nothing to the default value of that type.

Consider this overly simplified noncompliant code example, this function will never return Nothing, because the If(...) operator always returns a Date value instead of Date?. Here Nothing is converted to Date.MinValue instead of converting Date.Today.AddDays(days) to Date?.

Noncompliant code: always returns ‘Nothing’ as ‘Date.MinValue’

Public Function GetAddedDays(days As Integer) As Date?
    Return If(days < 0, Nothing, Date.Today.AddDays(days))
End Function 

This is probably not what the programmer intended and this is not the expected results. To make sure this function returns Nothing instead of Date.MinValue this is the compliant code:

Compliant code: returns ‘Nothing’ as expected

Public Function GetAddedDays(days As Integer) As Date?
    Return If(days < 0, CType(Nothing, Date?), Date.Today.AddDays(days))
End Function

In C#, this would not even compile and give you the following error:
Type of conditional expression cannot be determined because there is no implicit conversion between ‘null’ and ‘DateTime’


(Andrei Epure) #3

Thank you, @thorsteinn for this valuable rule suggestion!