简体   繁体   中英

How to handle null objects in string concatenations in VB.NET?

Dim response As MyClass = obj.ProcessRequest(strRequest)
Msgbox("This is the response message: " & response.Message)

If there is a problem in the ProcessRequest method and it returns null , then the next line will not work and a NullReference exception will be thrown.

What is the easiest way to have response.Message evaluate to an empty string if response is null ?

You may use inline If :

Msgbox("This is the response message: " & If(response Is Nothing, "", response.Message))

but IMO it is more readable to use if .. else clause

& Nothing equates to & "".

So the neatest way IMO is:

Dim response As MyClass = obj.ProcessRequest(strRequest)
Msgbox("This is the response message: " & response?.Message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM