mirror of
https://github.com/markjprice/cs11dotnet7.git
synced 2025-12-06 05:32:03 +01:00
Added item for page 244
This commit is contained in:
parent
8fe96c5f62
commit
ee316fde8a
18
vscode/Chapter05/PacktLibraryModern/Records.cs
Normal file
18
vscode/Chapter05/PacktLibraryModern/Records.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
namespace Packt.Shared;
|
||||
|
||||
public class ImmutablePerson
|
||||
{
|
||||
public string? FirstName { get; init; }
|
||||
public string? LastName { get; init; }
|
||||
}
|
||||
|
||||
public record ImmutableVehicle
|
||||
{
|
||||
public int Wheels { get; init; }
|
||||
public string? Color { get; init; }
|
||||
public string? Brand { get; init; }
|
||||
}
|
||||
|
||||
// simpler way to define a record
|
||||
// auto-generates the properties, constructor, and deconstructor
|
||||
public record ImmutableAnimal(string Name, string Species);
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
namespace Packt.Shared;
|
||||
|
||||
public class ImmutablePerson
|
||||
{
|
||||
//public string? FirstName { get; init; }
|
||||
//public string? LastName { get; init; }
|
||||
}
|
||||
|
|
@ -293,9 +293,28 @@ foreach (Passenger passenger in passengers)
|
|||
WriteLine($"Flight costs {flightCost:C} for {passenger}");
|
||||
}
|
||||
|
||||
//ImmutablePerson jeff = new()
|
||||
//{
|
||||
// FirstName = "Jeff",
|
||||
// LastName = "Winger"
|
||||
//};
|
||||
//jeff.FirstName = "Geoff";
|
||||
ImmutablePerson jeff = new()
|
||||
{
|
||||
FirstName = "Jeff",
|
||||
LastName = "Winger"
|
||||
};
|
||||
// We cannot set the properties after initialization because they
|
||||
// are init-only.
|
||||
// jeff.FirstName = "Geoff";
|
||||
|
||||
ImmutableVehicle car = new()
|
||||
{
|
||||
Brand = "Mazda MX-5 RF",
|
||||
Color = "Soul Red Crystal Metallic",
|
||||
Wheels = 4
|
||||
};
|
||||
|
||||
ImmutableVehicle repaintedCar = car
|
||||
with { Color = "Polymetal Grey Metallic" };
|
||||
|
||||
WriteLine($"Original car color was {car.Color}.");
|
||||
WriteLine($"New car color is {repaintedCar.Color}.");
|
||||
|
||||
ImmutableAnimal oscar = new("Oscar", "Labrador");
|
||||
var (who, what) = oscar; // calls Deconstruct method
|
||||
WriteLine($"{who} is a {what}.");
|
||||
|
|
|
|||
Loading…
Reference in a new issue