Skip to content

Instantly share code, notes, and snippets.

@richlander

richlander/Program.cs Secret

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

This comment has been minimized.

Copy link
Owner Author

@richlander richlander commented Sep 15, 2020

Produces the following output:

PS D:\git\batteryrecord> dotnet run
Battery { Model = CR2032, TotalCapacityAmpHours = 0.235, RemainingCapacityPercentage = 100 }
Battery { Model = CR2032, TotalCapacityAmpHours = 0.235, RemainingCapacityPercentage = 0 }

Alternate version, using mutable data: https://gist.github.com/richlander/83d2ccde88218e56e6b93a55db3f986b.

@Aaron-Lathrop

This comment has been minimized.

Copy link

@Aaron-Lathrop Aaron-Lathrop commented Nov 11, 2020

I'm confused, my understanding was that records are immutable and yet here we see battery being reassigned and effectively mutated.

Granted the original data in memory battery pointed to is in tact which will presumably be cleaned up by the GC.

Is this the point, to allow battery to have a reassigned reference for convenience as well as keeping memory cleaned up?

@empz

This comment has been minimized.

Copy link

@empz empz commented Nov 12, 2020

I'm confused, my understanding was that records are immutable and yet here we see battery being reassigned and effectively mutated.

Granted the original data in memory battery pointed to is in tact which will presumably be cleaned up by the GC.

Is this the point, to allow battery to have a reassigned reference for convenience as well as keeping memory cleaned up?

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 modified RemainingCapacityPercentage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment