What is the best way to mix VB.NET's Option Strict and the new Option Infer directives?

安稳与你 提交于 2019-11-28 13:24:27

Option Strict and Option Infer do not conflict, so I see no harm in having both on.

As a style guide, I prefer to put Option Strict, Explicit, and Infer at the top of each class file - this prevents differences in project or IDE settings from causing issues, and makes it clear what settings are used.

Option Strict can be used without Option Infer, but Option Infer should not be used without Option Strict as that can lead to a difference in the resulting IL.

Consider this line of code:

txtBox.Text = If(str="", Nothing, CDate(str))

With Option Strict Off and Option Infer Off, that is the equvalent of:

txtBox.Text = CStr(If(str="", Nothing, CType(CDate(str), Object)))

If str="" then txtBox.Text is set to Nothing/empty string.

With Option Infer On but Option Strict Off that becomes:

txtBox.Text = Cstr(If(str="", CDate(Nothing), CType(CDate(str), Object)))

And CDate(Nothing) = Date.MinValue and so txtBox.Text = "01/01/0001"

Option Strict can only make your code not compile, Option Infer can change its meaning. That is not to say that Infer can’t be a good thing, in general it is, but there are a few caveats that you need to be aware of.

The original code could be written as:

 txtBox.Text = Cstr(If(str="", Nothing, CDate(str)))

In which case Option Strict won’t save you if you turn Option. Infer On, but in a code base without Strict the original version is more likely.

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