Home >Backend Development >C#.Net Tutorial >What does $ in c# mean?
The $ symbol in C# has the following three main meanings: 1. String interpolation, used to embed expressions in strings; 2. Anonymous types, used to create temporary types whose properties and initializers Corresponding to the expressions in; 3. Pattern matching, used to match different expression patterns and specify operations.
$
in C# In C#, the $
symbol has the following meaning:
String Interpolation
#$
notation is used for string interpolation, allowing expressions to be embedded directly in a string. This allows us to easily insert variables, constants, and complex expressions into strings.
Syntax:
<code class="c#">$"字符串 {变量} 表达式"</code>
For example:
<code class="c#">int age = 25; string message = $"我的年龄是 {age}。";</code>
Anonymous type
$
The symbol is also used for anonymous type. It allows us to create an unnamed temporary type whose properties correspond to the expression in the initializer.
Syntax:
<code class="c#">new { 属性名 = 值, ... }</code>
For example:
<code class="c#">var person = new { Name = "Alice", Age = 25 };</code>
Pattern matching
In C# 9.0, $
Symbols are used for pattern matching. It allows us to match different expression patterns and specify different actions for each pattern.
Syntax:
<code class="c#">expression switch { pattern1 => expression1, pattern2 => expression2, ... }</code>
For example:
<code class="c#">switch (age) { case 18..25: Console.WriteLine("年轻人"); break; case 26..60: Console.WriteLine("中年人"); break; default: Console.WriteLine("老年人"); break; }</code>
The above is the detailed content of What does $ in c# mean?. For more information, please follow other related articles on the PHP Chinese website!