| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="TemperatureConverter.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | |
| | | 9 | | namespace MyNet.Primitives.Conversion; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides conversion between Celsius, Fahrenheit and Kelvin. |
| | | 13 | | /// </summary> |
| | | 14 | | public sealed class TemperatureConverter : IUnitConverter<TemperatureUnit> |
| | | 15 | | { |
| | | 16 | | public double Convert(double value, TemperatureUnit from, TemperatureUnit to) |
| | | 17 | | { |
| | 21 | 18 | | var celsius = ToCelsius(value, from); |
| | 21 | 19 | | return FromCelsius(celsius, to); |
| | | 20 | | } |
| | | 21 | | |
| | 21 | 22 | | private static double ToCelsius(double value, TemperatureUnit unit) => unit switch |
| | 21 | 23 | | { |
| | 12 | 24 | | TemperatureUnit.Celsius => value, |
| | 6 | 25 | | TemperatureUnit.Fahrenheit => (value - 32d) * 5d / 9d, |
| | 3 | 26 | | TemperatureUnit.Kelvin => value - 273.15d, |
| | 0 | 27 | | _ => throw new ArgumentOutOfRangeException(nameof(unit), unit, "Unsupported temperature unit.") |
| | 21 | 28 | | }; |
| | | 29 | | |
| | 21 | 30 | | private static double FromCelsius(double value, TemperatureUnit unit) => unit switch |
| | 21 | 31 | | { |
| | 6 | 32 | | TemperatureUnit.Celsius => value, |
| | 9 | 33 | | TemperatureUnit.Fahrenheit => (value * 9d / 5d) + 32d, |
| | 6 | 34 | | TemperatureUnit.Kelvin => value + 273.15d, |
| | 0 | 35 | | _ => throw new ArgumentOutOfRangeException(nameof(unit), unit, "Unsupported temperature unit.") |
| | 21 | 36 | | }; |
| | | 37 | | } |
| | | 38 | | |