Home > OS >  Underscore usage inside loop
Underscore usage inside loop

Time:12-23

Today, I encountered this new syntax in a C# program:

var sb = new StringBuilder();
foreach (var ns in this.Namespaces)
{
    _ = sb.AppendFormat(CultureInfo.InvariantCulture, " {0}", ns.Value);
}

The underscore inside the loop is never defined, and the code above seems to compile just fine. So I think the underscore is a syntactic sugar of some kind. But seems that my Google skill failed me this time (I found perl and python information about underscore, or a JS library named underscore).

So it's not clear to me the meaning of the underscore in the code snippet. Can someone clarify it to me? The code is taken from this library : https://www.nuget.org/packages/OpenGraph-Net/4.0.2-alpha.0.6

A Net Core 6.0 library written in C#

CodePudding user response:

The term you need to search for is discard variables - the underscore indicates that the variable is intentionally unused.

See here for more details.

  • Related