« Csharp 12 » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Aucun résumé des modifications
 
(2 versions intermédiaires par le même utilisateur non affichées)
Ligne 4 : Ligne 4 :


= [https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/primary-constructors Primary constructors] =
= [https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/primary-constructors Primary constructors] =
{{warn | Default value parameters must be compile time consistant.}}
<kode lang='cs'>
<kode lang='cs'>
public class Item
public class Item
Ligne 18 : Ligne 19 :
public class Item(string name)
public class Item(string name)
{
{
     public readonly string Name { get; } = name;
     public string Name { get; } = name;
}
}
</kode>
</kode>
Ligne 32 : Ligne 33 :
</kode>
</kode>


= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#ref-readonly-modifier ref readonly modifier] =
= [[Parameter_modifiers#ref_readonly|ref readonly modifier]] =
<kode lang='cs'>
var item = new Item("name");
ForceByRef(ref item);
 
static void ForceByRef(ref readonly Item item)
{
    item = new Item("new name"); // you can't assign a readonly variable
    item.Name = "new name";      // you can modify the object properties
}
</kode>

Dernière version du 16 septembre 2024 à 13:33

Links

Primary constructors

Default value parameters must be compile time consistant.
Cs.svg
public class Item
{
    public readonly string Name { get; }

    public Item (string name)
    {
        Name = name;
    }
}

// equivalent with a primary constructor
public class Item(string name)
{
    public string Name { get; } = name;
}

Collection Expressions

Cs.svg
// initialization
int[] a     = [1, 2, 3];
List<int> l = [4, 5, 6];

// concat items from different collections with the spread element: ..e
int[] all = [.. a, .. l]; // [1, 2, 3, 4, 5, 6];

ref readonly modifier