Using VB.NET IIF I get NullReferenceException

大憨熊 提交于 2019-11-26 20:30:45

问题


I am doing a little debugging, and so I want to log the eventArgs value

I have a simple line that basically does:

logLine = "e.Value: " + IIf(e.Value Is Nothing, "", e.Value.ToString())

The way I understand the IIF function, if the e.Value is Nothing (null) then it should return the empty string, if not it should return the .ToString of the value. I am, however getting a NullReferenceException. This doesn't make sense to me.

Any idea's?


回答1:


IIf is an actual function, so all arguments get evaluated. The If keyword was added to VB.NET 2008 to provide the short-circuit functionality you're expecting.

Try

logLine = "e.Value: " + If(e.Value Is Nothing, "", e.Value.ToString())



回答2:


VB does not do short-circuiting evaluation in Iif. In your case, e.Value.ToString() is being evaluated no matter whether e.Value is nothing.




回答3:


This is the expected behaviour.

IIF is a function; therefore the parameters for the function will be evaluated before sending it to the function.

In contrast, the ternary operator in C# is a language construct that prevents the evaluation of the second parameter if the expression of the ternary is true.



来源:https://stackoverflow.com/questions/428959/using-vb-net-iif-i-get-nullreferenceexception

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