I can't recall how many times I've written code like:
void fillInTextBox(Control someControl, string value)
{
TextBox textBox = someControl as TextBox;
if (textBox != null)
{
textBox.Text = value;
}
}
Starting with C# 7 pattern matching, we can combine this into one statement:
void fillInTextBox(Control someControl, string value)
{
if (someControl is TextBox textBox)
{
textBox.Text = value;
}
}
Now in one line. Much nicer!
Even works nicely with "is not"!
I found a rather unusual implementation of this, which caused me to have to try it myself. You can use this language feature along with an "is not" implementation, as seen here:
void OutputStringBuilder(object input)
{
if (input is not StringBuilder sb) return;
Console.WriteLine(sb.ToString());
}
What's odd about this interesting code, is that the sb is scoped to the rest of the function afer the if-statement; which is why the code in line 4 compiles fine. However if you removed the not in line3, line 4 would not compile, because those variables are only scoped within the if-block. Go figure...