VB.NET null coalescing operator? [duplicate]

柔情痞子 提交于 2019-12-17 15:59:15

问题


Possible Duplicates:
Coalesce operator and Conditional operator in VB.NET
Is there a VB.NET equivalent for C#'s ?? operator?

Is there a built-in VB.NET equivalent to the C# null coalescing operator?


回答1:


Yes, there is, a long as you're using VB 9 or later (included with Visual Studio 2008).

You can use the version of the If operator overloaded to accept only two arguments:

Dim myVar? As Integer = Nothing
Console.WriteLine(If(myVar, 7))

More information can be found here in a blog post by the VB.NET team.

(Yes, this is an operator, even though it looks like a function. It will compile down to the same IL as the "proper" null-coalescing operator in C#.)

Example

Dim b As Boolean?
Console.WriteLine("{0}.", If(b, "this is expected when b is nothing"))
'output: this is expected when b is nothing.

b = False
Console.WriteLine("{0}.", If(b, "this is unexpected when b is false"))
'output: False.

b = True
Console.WriteLine("{0}.", If(b, "this is unexpected when b is true"))
'output: True.



回答2:


According to this question it would seem the answer is If()




回答3:


No. Use GetValueOrDefault; that's why it's there!




回答4:


I don't believe that there is a built in VB.Net equivalent, but here's an answer: null coalesce operator in VB.Net(8)



来源:https://stackoverflow.com/questions/6792729/vb-net-null-coalescing-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!