SangYoung Ha
SangYoung Ha

Reputation: 1

C# While Loop Null Check Pattern?

I wrote code like this

using (var reader = new StreamReader("SomeFilePath"))
{
    while(reader.ReadLine() is string currentLine)
    {}
}

Then My IDE Rider suggested me below with comment "Use null check pattern"

using (var reader = new StreamReader("SomeFilePath"))
{
    while(reader.ReadLine() is {} currentLine)
    {}
}

I thought that would make syntax error, but it didn't

That Line Of Code does her job nicely.

So my question is what is {} in while(reader.ReadLine is {} currentLine)

maybe it's kind of Record Expression?

Also I could not figure out why {} currentLine is better than string currentLine

Thank you for your help

Upvotes: 0

Views: 492

Answers (2)

tomdinh
tomdinh

Reputation: 198

TLDR: { } is for pattern matching or Null checking, shorthand for If else statement.

Swift have the guard statement. Microsoft.Toolkit.Diagnostics have Guard Class, that is to highlight the important of null checking. The { } can also understand like a guard

So my question is what is {} in while(reader.ReadLine is {} currentLine)

The is operator checks if the result of an expression is compatible with a given type. your IDE Rider over reacting of comparing reader.ReadLine() with string both can be null, VS2022 give it a pass because ReadLine() is read null if the end of the input stream is reached.

Also I could not figure out why {} currentLine is better than string currentLine

Working with Null in .NET 6 and C# 10 I believe Rider want to make sure all cases are covered with { }, in most case with Reference type the IDE will give you warning of Null checking, to bypass this instead cheking with If else you just need { }

Upvotes: 0

Abhishek Dutt
Abhishek Dutt

Reputation: 1437

is {} is used to match an expression against a pattern.It uses the is operator (For C# versions >= 7.0 )

So basically this line of code:

while(reader.ReadLine() is {} currentLine)

checks if the output of reader.Readline() matches any pattern(i.e. not null). If it does, then assign the output to the variable currentLine .

Upvotes: 2

Related Questions