RSCG – OneOf
RSCG – OneOf
name | OneOf |
nuget |
https://www.nuget.org/packages/OneOf.SourceGenerator https://www.nuget.org/packages/OneOf/ |
link | https://github.com/mcintyre321/OneOf |
author | Harry McIntyre |
Functional discriminated unions
This is how you can use OneOf .
The code that you start with is
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net7.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="OneOf" Version="3.0.255" /> <PackageReference Include="OneOf.SourceGenerator" Version="3.0.255" /> </ItemGroup> <PropertyGroup> <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> <CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath> </PropertyGroup> </Project>
The code that you will use is
using OneOfDemo; Console.WriteLine("Please enter data - string or number"); var data= Console.ReadLine(); //you can experiment with StringOrNumber nr1 = 5; var nr = new StringOrNumber(data); var dataNumber = nr.TryGetNumber(); Console.WriteLine($"{dataNumber.isNumber} {dataNumber.number}");
using OneOf; namespace OneOfDemo; [GenerateOneOf] public partial class StringOrNumber : OneOfBase<string, int> { public (bool isNumber, int number) TryGetNumber() => Match( //this match function is auto generated s => (int.TryParse(s, out var n), n), i => (true, i) ); }
The code that is generated is
// <auto-generated /> using System; #pragma warning disable 1591 namespace OneOf { [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] internal sealed class GenerateOneOfAttribute : Attribute { } }
// <auto-generated /> #pragma warning disable 1591 namespace OneOfDemo { partial class StringOrNumber { public StringOrNumber(OneOf.OneOf<string, int> _) : base(_) { } public static implicit operator StringOrNumber(string _) => new StringOrNumber(_); public static explicit operator string(StringOrNumber _) => _.AsT0; public static implicit operator StringOrNumber(int _) => new StringOrNumber(_); public static explicit operator int(StringOrNumber _) => _.AsT1; } }
Code and pdf at
https://ignatandrei.github.io/RSCG_Examples/v2/docs/OneOf
Leave a Reply