Skip to content

Instantly share code, notes, and snippets.

@richlander

richlander/Program.cs Secret

Last active Sep 15, 2020
Embed
What would you like to do?
Records with mutable data
using System;
Battery battery = new Battery("CR2032", 0.235)
{
RemainingCapacityPercentage = 100
};
Console.WriteLine (battery);
for (int i = battery.RemainingCapacityPercentage; i >= 0; i--)
{
battery.RemainingCapacityPercentage = i;
}
Console.WriteLine (battery);
public record Battery(string Model, double TotalCapacityAmpHours)
{
public int RemainingCapacityPercentage {get;set;}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@richlander

This comment has been minimized.

Copy link
Owner Author

@richlander richlander commented Sep 13, 2020

Produces the following output:

rich@thundera recordmutable % dotnet run
Battery { Model = CR2032, TotalCapacityAmpHours = 0.235, RemainingCapacityPercentage = 100 }
Battery { Model = CR2032, TotalCapacityAmpHours = 0.235, RemainingCapacityPercentage = 0 }

Alternate version, using only immutable data: https://gist.github.com/richlander/bcbbcc9e0b541a06eb805d663ebf6334.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.