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?
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.
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.
Variable declarations. Before you can use a variable in C, you must declare it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With