« Record » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 37 : Ligne 37 :
}
}
</kode>
</kode>
= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record#immutability Immutability] =
Immutability means the data of the record don't change after its creation.<br>
It is useful when you need thread-safe data-centric types or expect hash codes remaining the sames.
= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record#value-equality Value equality] =
Two record objects are equal if they are of the same type and store the same values.

Version du 9 août 2024 à 13:41

Links

Definition

Built-in functionality for encapsulating immutable data.
C# 10 allows the record class syntax as a synonym to clarify a reference type, and record struct to define a value type.

Primary constructor

When you declare a primary constructor on a record, the compiler generates public properties for the primary constructor parameters.

Cs.svg
public record Person(string FirstName, string LastName);

// with the generated properties it is equivalent to
public record Person
{
    public required string FirstName { get; init; }
    public required string LastName { get; init; }
};

// record struct value type with immutable properties
public readonly record struct Point(double X, double Y);
// equivalent to
public record struct Point
{
    public double X { get; init; }
    public double Y { get; init; }
}

// record struct value type with mutable properties
public record struct Point(double X, double Y);
// equivalent to
public record struct Point
{
    public double X { get; set; }
    public double Y { get; set; }
}

Immutability

Immutability means the data of the record don't change after its creation.
It is useful when you need thread-safe data-centric types or expect hash codes remaining the sames.

Value equality

Two record objects are equal if they are of the same type and store the same values.