Inline variable declaration doesn't compile when using '== false' instead of negation operator

最后都变了- 提交于 2019-12-18 13:07:51

问题


Consider the following snippets:

void Foo(object sender, EventArgs e)
{
    if (!(sender is ComboBox comboBox)) return;
    comboBox.DropDownWidth = 100;
}

compared to

void Bar(object sender, EventArgs e)
{
    if ((sender is ComboBox comboBox) == false) return;
    comboBox.DropDownWidth = 100;
}

Code including Foo() successfully compiles in .Net 4.6.1, while code including Bar() results in Use of unassigned local variable 'comboBox'.

Without getting into a debate over the reasons behind using == false instead of the negation operator, can someone explain why one compiles and the other does not?


回答1:


Updated Answer Thanks to Julien opening a GitHub issue.

See Neal Gafter's response (copied here from here):

However, the error you're seeing is not about scope. It is about definite assignment. A pattern variable is definitely assigned when the pattern-matching expression is true. The unary ! operator reverses assigned-when-true and assigned-when-false. However, the boolean equality operator == throws away the distinction between assigned-when-true and assigned-when-false.


I believe the comboBox variable will only be created if the pattern matches.



来源:https://stackoverflow.com/questions/49523905/inline-variable-declaration-doesnt-compile-when-using-false-instead-of-neg

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