Home >Backend Development >C#.Net Tutorial >What does $ in c# mean?

What does $ in c# mean?

下次还敢
下次还敢Original
2024-04-04 14:03:211319browse

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.

What does $ in c# mean?

$

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn