Skip to content

Instantly share code, notes, and snippets.

@richlander
Last active September 15, 2020 05:53
Show Gist options
  • Save richlander/83d2ccde88218e56e6b93a55db3f986b to your computer and use it in GitHub Desktop.
Save richlander/83d2ccde88218e56e6b93a55db3f986b to your computer and use it in GitHub Desktop.
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
Copy link
Author

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