RSCG – N.SourceGenerators.UnionTypes

RSCG – N.SourceGenerators.UnionTypes
 
 

name N.SourceGenerators.UnionTypes
nuget https://www.nuget.org/packages/N.SourceGenerators.UnionTypes/
link https://github.com/Ne4to/N.SourceGenerators.UnionTypes
author Alexey Sosnin

Generating different union types

 

This is how you can use N.SourceGenerators.UnionTypes .

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="N.SourceGenerators.UnionTypes" Version="0.26.0" />
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>
</Project>


The code that you will use is


using UnionTypesDemo;

Console.WriteLine("Save or not");
var data = SaveToDatabase.Save(0);
Console.WriteLine(data.IsValidationError);
data = SaveToDatabase.Save(1);
Console.WriteLine(data.IsSuccess);



using N.SourceGenerators.UnionTypes;
namespace UnionTypesDemo;
public record Success(int Value);
public record ValidationError(string Message);

[UnionType(typeof(Success))]
[UnionType(typeof(ValidationError))]
public partial class ResultSave
{
}





namespace UnionTypesDemo;

public class SaveToDatabase
{
    public static ResultSave Save(int i)
    {
        if(i ==0)
        {
            return new ValidationError(" cannot save 0");
        }
        return new Success(i);
    }
}




 

The code that is generated is

// <auto-generated>
//   This code was generated by https://github.com/Ne4to/N.SourceGenerators.UnionTypes
//   Feel free to open an issue
// </auto-generated>
#nullable enable
using System;
using System.Runtime.CompilerServices;

namespace N.SourceGenerators.UnionTypes
{
    [AttributeUsage(AttributeTargets.GenericParameter, Inherited = false, AllowMultiple = false)]
    internal sealed class GenericUnionTypeAttribute : Attribute
    {
        public string? Alias { get; set; }
        public bool AllowNull { get; set; }
        public object? TypeDiscriminator { get; set; }
    }
}
// <auto-generated>
//   This code was generated by https://github.com/Ne4to/N.SourceGenerators.UnionTypes
//   Feel free to open an issue
// </auto-generated>
#nullable enable
using System;
using System.Runtime.CompilerServices;

namespace N.SourceGenerators.UnionTypes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)]
    internal sealed class JsonPolymorphicUnionAttribute : Attribute
    {
        public string? TypeDiscriminatorPropertyName { get; set; }
    }
}
// <auto-generated>
//   This code was generated by https://github.com/Ne4to/N.SourceGenerators.UnionTypes
//   Feel free to open an issue
// </auto-generated>
#pragma warning disable
#nullable enable
namespace UnionTypesDemo
{
    partial class ResultSave : System.IEquatable<ResultSave>
    {
        private readonly int _variantId;
        private const int SuccessId = 1;
        private readonly global::UnionTypesDemo.Success _success;
        public bool IsSuccess => _variantId == SuccessId;

        public global::UnionTypesDemo.Success AsSuccess
        {
            get
            {
                if (_variantId == SuccessId)
                    return _success;
                throw new System.InvalidOperationException($"Unable convert to Success. Inner value is {ValueAlias} not Success.");
            }
        }

        public ResultSave(global::UnionTypesDemo.Success success)
        {
            System.ArgumentNullException.ThrowIfNull(success);
            _variantId = SuccessId;
            _success = success;
        }

        public static implicit operator ResultSave(global::UnionTypesDemo.Success success) => new ResultSave(success);
        public static explicit operator global::UnionTypesDemo.Success(ResultSave value)
        {
            if (value._variantId == SuccessId)
                return value._success;
            throw new System.InvalidOperationException($"Unable convert to Success. Inner value is {value.ValueAlias} not Success.");
        }

        public bool TryGetSuccess([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::UnionTypesDemo.Success value)
        {
            if (_variantId == SuccessId)
            {
                value = _success;
                return true;
            }
            else
            {
                value = default;
                return false;
            }
        }

        private const int ValidationErrorId = 2;
        private readonly global::UnionTypesDemo.ValidationError _validationError;
        public bool IsValidationError => _variantId == ValidationErrorId;

        public global::UnionTypesDemo.ValidationError AsValidationError
        {
            get
            {
                if (_variantId == ValidationErrorId)
                    return _validationError;
                throw new System.InvalidOperationException($"Unable convert to ValidationError. Inner value is {ValueAlias} not ValidationError.");
            }
        }

        public ResultSave(global::UnionTypesDemo.ValidationError validationError)
        {
            System.ArgumentNullException.ThrowIfNull(validationError);
            _variantId = ValidationErrorId;
            _validationError = validationError;
        }

        public static implicit operator ResultSave(global::UnionTypesDemo.ValidationError validationError) => new ResultSave(validationError);
        public static explicit operator global::UnionTypesDemo.ValidationError(ResultSave value)
        {
            if (value._variantId == ValidationErrorId)
                return value._validationError;
            throw new System.InvalidOperationException($"Unable convert to ValidationError. Inner value is {value.ValueAlias} not ValidationError.");
        }

        public bool TryGetValidationError([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out global::UnionTypesDemo.ValidationError value)
        {
            if (_variantId == ValidationErrorId)
            {
                value = _validationError;
                return true;
            }
            else
            {
                value = default;
                return false;
            }
        }

        public TOut Match<TOut>(global::System.Func<global::UnionTypesDemo.Success, TOut> matchSuccess, global::System.Func<global::UnionTypesDemo.ValidationError, TOut> matchValidationError)
        {
            if (_variantId == SuccessId)
                return matchSuccess(_success);
            if (_variantId == ValidationErrorId)
                return matchValidationError(_validationError);
            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public async global::System.Threading.Tasks.Task<TOut> MatchAsync<TOut>(global::System.Func<global::UnionTypesDemo.Success, global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task<TOut>> matchSuccess, global::System.Func<global::UnionTypesDemo.ValidationError, global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task<TOut>> matchValidationError, global::System.Threading.CancellationToken ct)
        {
            if (_variantId == SuccessId)
                return await matchSuccess(_success, ct).ConfigureAwait(false);
            if (_variantId == ValidationErrorId)
                return await matchValidationError(_validationError, ct).ConfigureAwait(false);
            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public void Switch(global::System.Action<global::UnionTypesDemo.Success> switchSuccess, global::System.Action<global::UnionTypesDemo.ValidationError> switchValidationError)
        {
            if (_variantId == SuccessId)
            {
                switchSuccess(_success);
                return;
            }

            if (_variantId == ValidationErrorId)
            {
                switchValidationError(_validationError);
                return;
            }

            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public async global::System.Threading.Tasks.Task SwitchAsync(global::System.Func<global::UnionTypesDemo.Success, global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task> switchSuccess, global::System.Func<global::UnionTypesDemo.ValidationError, global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task> switchValidationError, global::System.Threading.CancellationToken ct)
        {
            if (_variantId == SuccessId)
            {
                await switchSuccess(_success, ct).ConfigureAwait(false);
                return;
            }

            if (_variantId == ValidationErrorId)
            {
                await switchValidationError(_validationError, ct).ConfigureAwait(false);
                return;
            }

            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public global::System.Type ValueType
        {
            get
            {
                if (_variantId == SuccessId)
                    return typeof(global::UnionTypesDemo.Success);
                if (_variantId == ValidationErrorId)
                    return typeof(global::UnionTypesDemo.ValidationError);
                throw new System.InvalidOperationException("Inner type is unknown");
            }
        }

        private string ValueAlias
        {
            get
            {
                if (_variantId == SuccessId)
                    return "Success";
                if (_variantId == ValidationErrorId)
                    return "ValidationError";
                throw new System.InvalidOperationException("Inner type is unknown");
            }
        }

        public override int GetHashCode()
        {
            if (_variantId == SuccessId)
                return _success.GetHashCode();
            if (_variantId == ValidationErrorId)
                return _validationError.GetHashCode();
            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public static bool operator ==(ResultSave? left, ResultSave? right)
        {
            return Equals(left, right);
        }

        public static bool operator !=(ResultSave? left, ResultSave? right)
        {
            return !Equals(left, right);
        }

        public bool Equals(ResultSave? other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }

            if (ReferenceEquals(this, other))
            {
                return true;
            }

            if (ValueType != other.ValueType)
            {
                return false;
            }

            if (_variantId == SuccessId)
                return System.Collections.Generic.EqualityComparer<global::UnionTypesDemo.Success>.Default.Equals(_success, other._success);
            if (_variantId == ValidationErrorId)
                return System.Collections.Generic.EqualityComparer<global::UnionTypesDemo.ValidationError>.Default.Equals(_validationError, other._validationError);
            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public override string ToString()
        {
            if (_variantId == SuccessId)
                return _success.ToString();
            if (_variantId == ValidationErrorId)
                return _validationError.ToString();
            throw new System.InvalidOperationException("Inner type is unknown");
        }

        public override bool Equals(object? other)
        {
            if (ReferenceEquals(null, other))
            {
                return false;
            }

            if (ReferenceEquals(this, other))
            {
                return true;
            }

            if (other.GetType() != typeof(ResultSave))
            {
                return false;
            }

            return Equals((ResultSave)other);
        }
    }
}
#nullable enable
using System;
using System.Runtime.CompilerServices;

namespace N.SourceGenerators.UnionTypes
{
    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
    sealed class UnionConverterAttribute : Attribute
    {
        public Type FromType { get; }
        public Type ToType { get; }
        public string? MethodName { get; }

        public UnionConverterAttribute(Type fromType, Type toType, string? methodName = null)
        {
            FromType = fromType;
            ToType = toType;
            MethodName = methodName;
        }
    }
}
// <auto-generated>
//   This code was generated by https://github.com/Ne4to/N.SourceGenerators.UnionTypes
//   Feel free to open an issue
// </auto-generated>
#nullable enable
using System;
using System.Runtime.CompilerServices;

namespace N.SourceGenerators.UnionTypes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
    sealed class UnionConverterFromAttribute : Attribute
    {
        public Type FromType { get; }

        public UnionConverterFromAttribute(Type fromType)
        {
            FromType = fromType;
        }
    }
}
// <auto-generated>
//   This code was generated by https://github.com/Ne4to/N.SourceGenerators.UnionTypes
//   Feel free to open an issue
// </auto-generated>
#nullable enable
using System;
using System.Runtime.CompilerServices;

namespace N.SourceGenerators.UnionTypes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
    sealed class UnionConverterToAttribute : Attribute
    {
        public Type ToType { get; }

        public UnionConverterToAttribute(Type toType)
        {
            ToType = toType;
        }
    }
}
// <auto-generated>
//   This code was generated by https://github.com/Ne4to/N.SourceGenerators.UnionTypes
//   Feel free to open an issue
// </auto-generated>
#nullable enable
using System;
using System.Runtime.CompilerServices;

namespace N.SourceGenerators.UnionTypes
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = true)]
    internal sealed class UnionTypeAttribute : Attribute
    {
        public Type Type { get; }
        public string? Alias { get; }
        public int Order { get; }
        public bool AllowNull { get; set; }
        public object? TypeDiscriminator { get; set; }

        public UnionTypeAttribute(Type type, string? alias = null, [CallerLineNumber] int order = 0)
        {
            Type = type;
            Alias = alias;
            Order = order;
        }
    }
}

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/N.SourceGenerators.UnionTypes