Does the VB.NET “If” operator cause boxing?

后端 未结 2 1211
孤街浪徒
孤街浪徒 2020-12-20 11:19

Those of us who\'ve worked in VB/VB.NET have seen code similar to this abomination:

Dim name As String = IIf(obj Is Nothing, \"\", obj.Name)
<
2条回答
  •  有刺的猬
    2020-12-20 12:08

    The main thing is that you correctly identified the new If as an operator rather than a function. It is also typesafe and therefore does not need boxing, and is a direct mapping to the conditional/ternary/? operator in C/C++/C#/Java/etc

    Even without the new operator, you can get some improvement in VB.Net with this code:

    Public Shared Function IIf(Of T)(ByVal Expression As Boolean, ByVal TruePart As T, ByVal FalsePart As T) As T
        If Expression Then Return TruePart Else Return FalsePart
    End Function
    

提交回复
热议问题