From ee316fde8ab573b046c77e8f44a124bc297eef4e Mon Sep 17 00:00:00 2001 From: Mark J Price Date: Thu, 10 Nov 2022 22:05:48 +0000 Subject: [PATCH] Added item for page 244 --- .../Chapter05/PacktLibraryModern/Records.cs | 18 +++++++++++ .../PacktLibraryNetStandard2/Records.cs | 7 ----- vscode/Chapter05/PeopleApp/Program.cs | 31 +++++++++++++++---- 3 files changed, 43 insertions(+), 13 deletions(-) create mode 100644 vscode/Chapter05/PacktLibraryModern/Records.cs delete mode 100644 vscode/Chapter05/PacktLibraryNetStandard2/Records.cs diff --git a/vscode/Chapter05/PacktLibraryModern/Records.cs b/vscode/Chapter05/PacktLibraryModern/Records.cs new file mode 100644 index 0000000..096d29d --- /dev/null +++ b/vscode/Chapter05/PacktLibraryModern/Records.cs @@ -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); \ No newline at end of file diff --git a/vscode/Chapter05/PacktLibraryNetStandard2/Records.cs b/vscode/Chapter05/PacktLibraryNetStandard2/Records.cs deleted file mode 100644 index bfb2a46..0000000 --- a/vscode/Chapter05/PacktLibraryNetStandard2/Records.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace Packt.Shared; - -public class ImmutablePerson -{ - //public string? FirstName { get; init; } - //public string? LastName { get; init; } -} diff --git a/vscode/Chapter05/PeopleApp/Program.cs b/vscode/Chapter05/PeopleApp/Program.cs index f80431d..f57c114 100644 --- a/vscode/Chapter05/PeopleApp/Program.cs +++ b/vscode/Chapter05/PeopleApp/Program.cs @@ -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}.");