Skip to content

IT CSharp Keyword with

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: with

Manuale C# · Guida pratica

Crea una copia modificata di un record, una struttura o un oggetto anonimo. I collegamenti incorporati vengono copiati superficialmente.

Esempio semplice (Example.cs)

Salvare questo esempio separatamente come Example.cs. Eseguirlo indipendentemente dagli altri esempi di questa pagina.

Example.cs:

// PROJECT-EXAMPLE
var original = new Item("ore", 1);
var copy = original with { Count = 3 };
System.Console.WriteLine($"{original.Count}:{copy.Count}");
record Item(string Name, int Count);

Risultato:

1:3

Sintassi

var changed = original with { Member = value };

Esempio 1: forma base

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Person first = new("Archer", 2);
        Person next = first with { Level = 3 };
        Console.WriteLine($"{first.Level}:{next.Level}");
    }
}
public record Person(string Name, int Level);

Esempio 2: un'altra forma pratica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        var first = new { Name = "Ore", Count = 5 };
        var next = first with { Count = 8 };
        Console.WriteLine($"{first.Count}:{next.Count}");
    }
}

Fonte ufficiale: Microsoft Impara.

Clone this wiki locally