Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-7.0

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?

like image 686
brainbolt Avatar asked Mar 27 '18 23:03

brainbolt


People also ask

Can we declare variable anywhere in C?

Modern C compilers such as gcc and clang support the C99 and C11 standards, which allow you to declare a variable anywhere a statement could go. The variable's scope starts from the point of the declaration to the end of the block (next closing brace). You can also declare variables inside for loop initializers.

How do you declare a variable inside an if statement in C++?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement.

Do you need to declare variables in C?

Variable declarations. Before you can use a variable in C, you must declare it.

What is variable declaration example?

a) General syntax for declaring a variable Eg:- char Final_Grade; // Final_Grade is a variable of type char, and no value is assigned to it. data_type variable_name = val; Eg:- int age = 22; // age is a variable of type int and holds the value 22. Here, data_type specifies the type of variable like int, char, etc.


1 Answers

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.

like image 111
Michael Minton Avatar answered Oct 12 '22 23:10

Michael Minton