Tricks and Tips: Make your code better with ‘IS’
Let me show you how the is operator in C# can revolutionize your code, making it more elegant, readable, and powerful. Since C# 7, this operator has evolved beyond its humble beginnings as a basic type-testing tool. It’s now a game-changer, offering a treasure trove of functionalities that empower developers to write cleaner, more expressive, and highly efficient code. With each new version of C#, the is operator has been enriched with incredible enhancements, unlocking new possibilities that truly elevate your programming experience. If you haven’t explored its full potential yet, prepare to be amazed—this is one feature you’ll wonder how you ever lived without!
Notable enhancements include:
- Declaration and Type Patterns
- Constant Pattern
- Pattern Combinators
- Property Patterns
For a complete list, refer to the following resources:
The is operator - Match an expression against a type or constant pattern - C#
Patterns - Pattern matching using the is and switch expressions - C#
Declaration and Type Patterns
A better version of is itself, allowing not only type checks but also variable declarations with the required type:
if (message is string stringMessage)
{
Console.WriteLine($"Casted object to string: {stringMessage}");
}
Constant Pattern
Use a constant pattern to verify whether an expression matches a specific constant value:
int? a = 10;
if (a is not null)
{
}
if (a is 10)
{
}
Pattern Combinators
Construct logical patterns using not, and, and or combinators. These allow validation of ranges or combining multiple conditions:
static bool IsLetter(char c) => c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z');
static bool IsIn100Range(int number) => number is >= 0 and <= 100;
Keep in mind the precedence of pattern combinators:
- not
- and
- or
Property Patterns
This is my favorite feature as it makes code very clear. Property patterns validate and compare property values within expressions. They ensure that properties or fields of an expression match specified values. Each corresponding property or field must equate for a successful match, and the expression must not be null.
var collection = new List<TestName>()
{
new TestName() { Name = "Name1" },
new TestName() { Name = "Name2", IsActive = true }
};
// Property Patterns
foreach (var item in collection.Where(item => item is { IsActive: true } or { Name: "Name1" }))
{
Console.WriteLine(item.Name);
}
public class TestName
{
public string Name { get; set; }
public bool? IsActive { get; set; }
}
Output:
Name1
Name2
These enhancements to the is operator demonstrate its versatility and usefulness in various scenarios.