From fde1a6089c8e466a41bd8207a643ba13ff16d7ea Mon Sep 17 00:00:00 2001 From: Selene29 Date: Sat, 7 Mar 2026 23:38:33 +0100 Subject: [PATCH] Add Fraction/decimal/double/int From overloads to codegen template Adds From overloads for all number types (Fraction, decimal, double, int) plus their nullable variants to the UnitGenerator template, matching the constructor order. All generated unit classes will support these factory method overloads. --- CodeGen/Code/UnitGenerator.cs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/CodeGen/Code/UnitGenerator.cs b/CodeGen/Code/UnitGenerator.cs index 51a94b90..71abd6c4 100644 --- a/CodeGen/Code/UnitGenerator.cs +++ b/CodeGen/Code/UnitGenerator.cs @@ -92,16 +92,46 @@ public partial class {{Variable}} : BaseUnit public {{Variable}}(int value, {{Variable}}Unit selectedUnit) : base(value, selectedUnit.Unit) { } public {{Variable}}(UnknownUnit value) : base(value) { } + public static {{Variable}} From(Fraction value, {{Variable}}Unit unit) => new(value, unit); + public static {{Variable}} From(decimal value, {{Variable}}Unit unit) => new(value, unit); public static {{Variable}} From(double value, {{Variable}}Unit unit) => new(value, unit); - + public static {{Variable}} From(int value, {{Variable}}Unit unit) => new(value, unit); + + [return: NotNullIfNotNull(nameof(value))] + public static {{Variable}}? From(Fraction? value, {{Variable}}Unit? unit) + { + if (value is null || unit is null) + return null; + + return From((Fraction)value, unit); + } + + [return: NotNullIfNotNull(nameof(value))] + public static {{Variable}}? From(decimal? value, {{Variable}}Unit? unit) + { + if (value is null || unit is null) + return null; + + return From((decimal)value, unit); + } + [return: NotNullIfNotNull(nameof(value))] public static {{Variable}}? From(double? value, {{Variable}}Unit? unit) { if (value is null || unit is null) return null; - + return From((double)value, unit); } + + [return: NotNullIfNotNull(nameof(value))] + public static {{Variable}}? From(int? value, {{Variable}}Unit? unit) + { + if (value is null || unit is null) + return null; + + return From((int)value, unit); + } public double As({{Variable}}Unit ReturnInThisUnit) => this.GetValueAsDouble(ReturnInThisUnit); public {{Variable}} ToUnit({{Variable}}Unit selectedUnit) => new(this.GetValueAs(selectedUnit.Unit), selectedUnit); public static {{Variable}} Zero => new(0, {{Variable}}Unit.SI);