Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created Oct 20, 2021
Embed
What would you like to do?
using System;
using Xunit;
namespace ValueObject
{
public abstract record UnitOfMeasure;
public record Kilometers : UnitOfMeasure;
public record Miles : UnitOfMeasure;
public record Distance
{
public UnitOfMeasure UnitOfMeasure { get; }
public decimal Value { get; }
public Distance(UnitOfMeasure unitOfMeasure, decimal value)
{
UnitOfMeasure = unitOfMeasure;
Value = value;
}
public Distance ToMiles()
{
switch (UnitOfMeasure)
{
case Miles:
return new Distance(new Miles(), Value);
case Kilometers:
return new Distance(new Miles(), Math.Round(Value * 0.621371m, 2, MidpointRounding.AwayFromZero));
default:
throw new InvalidOperationException();
}
}
public Distance ToKilometers()
{
switch (UnitOfMeasure)
{
case Miles:
return new Distance(new Kilometers(), Math.Round(Value * 1.60934m, 2, MidpointRounding.AwayFromZero));
case Kilometers:
return new Distance(new Kilometers(), Value);
default:
throw new InvalidOperationException();
}
}
}
public class DistanceTest
{
[Fact]
public void Test()
{
var distance1 = new Distance(new Kilometers(), 100);
var distance2 = distance1.ToMiles();
var distance3 = distance2.ToKilometers();
Assert.Equal(distance3, distance1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment