-
-
Save richlander/bcbbcc9e0b541a06eb805d663ebf6334 to your computer and use it in GitHub Desktop.
Battery example using 'with'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>net5.0</TargetFramework> | |
<LangVersion>preview</LangVersion> | |
<Nullable>enable</Nullable> | |
</PropertyGroup> | |
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
Battery battery = new("CR2032", 0.235, 100); | |
Console.WriteLine (battery); | |
while (battery.RemainingCapacityPercentage > 0) | |
{ | |
Battery updatedBattery = battery with {RemainingCapacityPercentage = battery.RemainingCapacityPercentage - 1}; | |
battery = updatedBattery; | |
} | |
Console.WriteLine (battery); | |
public record Battery(string Model, double TotalCapacityAmpHours, int RemainingCapacityPercentage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inmutable means you can't modify its properties. It doesn't mean you can't reassign a variable to a new record. The
with
is basically generating a clone of the battery but with a modifiedRemainingCapacityPercentage
.