SoFunction
Updated on 2025-03-07

How to improve the aesthetics of if statements using the new C#9.0 syntax

Preface

C# language always adheres to the principle of simplicity and beauty. Each upgrade will bring some syntax sugar, allowing us to make the code more concise. This article shares two examples of tips for using C# 9.0 to improve the beauty of if statements.

Use attribute mode instead of IsNullOrEmpty

Whenever you use IsNullOrEmpty, you can consider replacing this:

string? hello = "hello world";
hello = null;

// Old wayif (!(hello))
{
 ($"{hello} has {} letters.");
}

// New wayif (hello is { Length: >0 })
{
 ($"{hello} has {} letters.");
}

The attribute mode is quite flexible, you can also use it on arrays to make various judgments on arrays. For example, determine whether the string element in the nullable string array is empty or blank:

string?[]? greetings = new string[2];
greetings[0] = "Hello world";
greetings = null;

// Old wayif (greetings != null && !(greetings[0]))
{
 ($"{greetings[0]} has {greetings[0].Length} letters.");
}

// New wayif (greetings?[0] is {Length: > 0} hi)
{
 ($"{hi} has {} letters.");
}

At the beginning, you may feel that the reading experience is not very good, but if you use it too much, you will read it too much. This concise method is more conducive to reading.

Use logical mode to simplify multiple judgments

For the same value, compare it with multiple other values ​​and can be simplified by using or , and logical modes. Example:

ConsoleKeyInfo userInput = ();

// Old wayif ( == 'Y' ||  == 'y')
{
 ("Do something.");
}

// New wayif ( is 'Y' or 'y')
{
 ("Do something.");
}

Many people have not understood why C# 9.0 introduced or and logical keywords, and it is clear at a glance through this example.

I will continue to share some new postures of C# 9.0 later, and I look forward to your sharing.

Summarize

This is the article about how to improve the aesthetics of if statements using the new C#9.0 syntax. This is all about this article. For more related contents of new C#9.0 syntax to improve if statements, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!