“Use of unassigned local variable” in if statement with TryParse with the use of dynamic

纵饮孤独 提交于 2019-12-05 13:59:25

This was a breaking change in Roslyn, documented here:

The definite assignment rules implemented by previous compilers for dynamic expressions allowed some cases of code that could result in variables being read that are not definitely assigned. See https://github.com/dotnet/roslyn/issues/4509 for one report of this.

[snip illustrative example]

Because of this possibility the compiler must not allow this program to be compiled if val has no initial value. Previous versions of the compiler (prior to VS2015) allowed this program to compile even if val has no initial value. Roslyn now diagnoses this attempt to read a possibly uninitialized variable.

This is because you use the short circuit operator &&, which means that if the first TryParse returns false, the second TryParse is never executed thus leaving the ToDate variable unassigned.

Try it, replace && by & and your error will disappear because both TryParse calls will now be always executed.

The compiler is just not clever enough (it doesn't analyse your logic) to know that the code inside won't be executed in some cases.

EDIT: @Simon, I've re-read your question and found that you already knew this... Maybe it's because .ToString always exist on an object but not always on a dynamic (for example when it's a com object), and in that case the compiler does less checks?

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