The if-cast-null-check feature for C#

1/13/2022

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!


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET/Core
  • T-SQL
  • HTML/Javascript/jQuery
  • ASP.NET/MVC
  • .NET Core
  • ADO.NET/EF
  • WPF
  • Xamarin/MAUI
  • Windows 10
  • SQL Server 20xx
  • Android
  • XBox One
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking