C# Source Generator to create Value object pattern, also inspired by units of measure to support all arithmetic operators and serialization.
NuGet: UnitGenerator
Install-Package UnitGenerator
Execute in Unity Game Engine is also supported, please see the Unity section for details.
For example, Identifier, UserId is comparable only to UserId, and cannot be assigned to any other type. Also, arithmetic operations are not allowed.
usingUnitGenerator;[UnitOf(typeof(int))]publicreadonlypartialstructUserId;{}or when using C#11 and NET7 you can use
usingUnitGenerator;[UnitOf<int>]publicreadonlypartialstructUserId;will generates
[System.ComponentModel.TypeConverter(typeof(UserIdTypeConverter))]publicreadonlypartialstructUserId:IEquatable<UserId>{readonlyintvalue;publicUserId(intvalue){this.value=value;}publicreadonlyintAsPrimitive()=>value;publicstaticexplicitoperatorint(UserIdvalue)=>value.value;publicstaticexplicitoperatorUserId(intvalue)=>newUserId(value);publicboolEquals(UserIdother)=>value.Equals(other.value);publicoverrideboolEquals(object?obj)=>// snip...publicoverride int GetHashCode()=>value.GetHashCode();publicoverridestringToString()=>value.ToString();publicstaticbooloperator==(inUserIdx,inUserIdy)=>x.value.Equals(y.value);publicstaticbooloperator!=(inUserIdx,inUserIdy)=>!x.value.Equals(y.value);privateclassUserIdTypeConverter:System.ComponentModel.TypeConverter{// snip...}}However, Hp in games, should not be allowed to be assigned to other types, but should support arithmetic operations with int. For example double heal = target.Hp = Hp.Min(target.Hp * 2, target.MaxHp).
[UnitOf<int>(UnitGenerateOptions.ArithmeticOperator|UnitGenerateOptions.ValueArithmeticOperator|UnitGenerateOptions.Comparable|UnitGenerateOptions.MinMaxMethod)]publicreadonlypartialstructHp;// -- generates[System.ComponentModel.TypeConverter(typeof(HpTypeConverter))]publicreadonlypartialstructHp:IEquatable<Hp>
#if NET7_0_OR_GREATER
,IEqualityOperators<Hp,Hp,bool>
#endif ,IComparable<Hp>
#if NET7_0_OR_GREATER
,IComparisonOperators<Hp,Hp,bool>
#endif
#if NET7_0_OR_GREATER
,IAdditionOperators<Hp,Hp,Hp>,ISubtractionOperators<Hp,Hp,Hp>,IMultiplyOperators<Hp,Hp,Hp>,IDivisionOperators<Hp,Hp,Hp>,IUnaryPlusOperators<Hp,Hp>,IUnaryNegationOperators<Hp,Hp>,IIncrementOperators<Hp>,IDecrementOperators<Hp>
#endif {readonlyintvalue;publicHp(intvalue){this.value=value;}publicintAsPrimitive()=>value;publicstaticexplicitoperatorint(Hpvalue)=>value.value;publicstaticexplicitoperatorHp(intvalue)=>newHp(value);publicboolEquals(Hpother)=>value.Equals(other.value);publicoverrideboolEquals(object?obj)=>// snip...publicoverride int GetHashCode()=>value.GetHashCode();publicoverridestringToString()=>value.ToString();publicstaticbooloperator==(inHpx,inHpy)=>x.value.Equals(y.value);publicstaticbooloperator!=(inHpx,inHpy)=>!x.value.Equals(y.value);privateclassHpTypeConverter:System.ComponentModel.TypeConverter{/* snip... */}// UnitGenerateOptions.ArithmeticOperatorpublicstaticHpoperator+(Hpx,Hpy)=>newHp(checked((int)(x.value+y.value)));publicstaticHpoperator-(Hpx,Hpy)=>newHp(checked((int)(x.value-y.value)));publicstaticHpoperator*(Hpx,Hpy)=>newHp(checked((int)(x.value*y.value)));publicstaticHpoperator/(Hpx,Hpy)=>newHp(checked((int)(x.value/y.value)));publicstaticHpoperator++(Hpx)=>newHp(checked((int)(x.value+1)));publicstaticHpoperator--(Hpx)=>newHp(checked((int)(x.value-1)));publicstaticHpoperator+(Avalue)=>new((int)(+value.value));publicstaticHpoperator-(Avalue)=>new((int)(-value.value));// UnitGenerateOptions.ValueArithmeticOperatorpublicstaticHpoperator+(Hpx,ininty)=>newHp(checked((int)(x.value+y)));publicstaticHpoperator-(Hpx,ininty)=>newHp(checked((int)(x.value-y)));publicstaticHpoperator*(Hpx,ininty)=>newHp(checked((int)(x.value*y)));publicstaticHpoperator/(Hpx,ininty)=>newHp(checked((int)(x.value/y)));// UnitGenerateOptions.ComparablepublicintCompareTo(Hpother)=>value.CompareTo(other.value);publicstaticbooloperator>(Hpx,Hpy)=>x.value>y.value;publicstaticbooloperator<(Hpx,Hpy)=>x.value<y.value;publicstaticbooloperator>=(Hpx,Hpy)=>x.value>=y.value;publicstaticbooloperator<=(Hpx,Hpy)=>x.value<=y.value;// UnitGenerateOptions.MinMaxMethodpublicstaticHpMin(Hpx,Hpy)=>newHp(Math.Min(x.value,y.value));publicstaticHpMax(Hpx,Hpy)=>newHp(Math.Max(x.value,y.value));}You can configure with UnitGenerateOptions, which method to implement.
[Flags]enumUnitGenerateOptions{None=0,ImplicitOperator=1,ParseMethod=1<<1,MinMaxMethod=1<<2,ArithmeticOperator=1<<3,ValueArithmeticOperator=1<<4,Comparable=1<<5,Validate=1<<6,JsonConverter=1<<7,MessagePackFormatter=1<<8,DapperTypeHandler=1<<9,EntityFrameworkValueConverter=1<<10,WithoutComparisonOperator=1<<11,JsonConverterDictionaryKeySupport=1<<12,Normalize=1<<13,}UnitGenerateOptions has some serializer support. For example, a result like Serialize(userId) => { Value = 1111 } is awful. The value-object should be serialized natively, i.e. Serialize(useId) => 1111, and should be able to be added directly to a database, etc.
Currently UnitGenerator supports MessagePack for C#, System.Text.Json(JsonSerializer), Dapper and EntityFrameworkCore.
[UnitOf<int>(UnitGenerateOptions.MessagePackFormatter)]publicreadonlypartialstructUserId;// -- generates[MessagePackFormatter(typeof(UserIdMessagePackFormatter))]publicreadonlypartialstructUserId{classUserIdMessagePackFormatter:IMessagePackFormatter<UserId>{publicvoidSerialize(refMessagePackWriterwriter,UserIdvalue,MessagePackSerializerOptionsoptions){options.Resolver.GetFormatterWithVerify<int>().Serialize(refwriter,value.value,options);}publicUserIdDeserialize(refMessagePackReaderreader,MessagePackSerializerOptionsoptions){returnnewUserId(options.Resolver.GetFormatterWithVerify<int>().Deserialize(refreader,options));}}}When referring to the UnitGenerator, it generates a internal UnitOfAttribute.
namespaceUnitGenerator{[AttributeUsage(AttributeTargets.Struct,AllowMultiple=false)]internalclassUnitOfAttribute:Attribute{publicTypeType{get;}publicUnitGenerateOptionsOptions{get;}publicUnitArithmeticOperatorsArithmeticOperators{get;set;}publicstring?ToStringFormat{get;set;}publicUnitOfAttribute(Typetype,UnitGenerateOptionsoptions=UnitGenerateOptions.None){ ...}}
#if NET7_0_OR_GREATER[AttributeUsage(AttributeTargets.Struct,AllowMultiple=false)]internalclassUnitOfAttribute<T>:Attribute{publicTypeType{get;}publicUnitGenerateOptionsOptions{get;}publicUnitArithmeticOperatorsArithmeticOperators{get;set;}=UnitArithmeticOperators.All;publicstring?ToStringFormat{get;set;}publicUnitOfAttribute(UnitGenerateOptionsoptions=UnitGenerateOptions.None){this.Type=typeof(T);this.Options=options;}}
#endif
}You can attach this attribute with any specified underlying type to readonly partial struct.
[UnitOf(typeof(Guid))]publicreadonlypartialstructGroupId{}[UnitOf(typeof(string))]publicreadonlypartialstructMessage{}[UnitOf(typeof(long))]publicreadonlypartialstructPower{}[UnitOf(typeof(byte[]))]publicreadonlypartialstructImage{}[UnitOf(typeof(DateTime))]publicreadonlypartialstructStartDate{}[UnitOf(typeof((stringstreet,stringcity)))]publicreadonlypartialstructStreetAddress{}Standard UnitOf(UnitGenerateOptions.None) generates value constructor, explicit operator, implement IEquatable<T>, override GetHashCode, override ToString, == and != operator, TypeConverter for ASP.NET Core binding, AsPrimitive method.
If you want to retrieve primitive value, use AsPrimitive() instead of .Value. This is intended to avoid casual getting of primitive values (using the arithmetic operator option if available).
When type is bool, also implements
true,false,!operators.
publicstaticbooloperator true(Foox)=>x.value;publicstaticbooloperator false(Foox)=>!x.value;publicstaticbooloperator!(Foox)=>!x.value;When type is Guid or Ulid, also implements
New()andNew***()static operator.
For Guid type in .NET 9.0 or later, these methods accept an optionaluuidV7parameter. WhenuuidV7is set totrue, the methods useGuid.CreateVersion7()internally.
publicstaticGroupIdNew();publicstaticGroupIdNewGroupId();// overload .NET 9.0+publicstaticGroupIdNew(booluuidV7);publicstaticGroupIdNewGroupId(booluuidV7);Second parameter UnitGenerateOptions options can configure which method to implement, default is None.
Optional named parameter: ArithmeticOperators can configure which generates operators specifically. Default is Number. (This can be used if UnitGenerateOptions.ArithmeticOperator is specified.)
Optional named parameter: ToStringFormat can configure ToString format. Default is null and output as ${0}.
When referring to the UnitGenerator, it generates a internal UnitGenerateOptions that is bit flag of which method to implement.
[Flags]internalenumUnitGenerateOptions{None=0,ImplicitOperator=1,ParseMethod=2,MinMaxMethod=4,ArithmeticOperator=8,ValueArithmeticOperator=16,Comparable=32,Validate=64,JsonConverter=128,MessagePackFormatter=256,DapperTypeHandler=512,EntityFrameworkValueConverter=1024,}You can use this with [UnitOf].
[UnitOf(typeof(int),UnitGenerateOptions.ArithmeticOperator|UnitGenerateOptions.ValueArithmeticOperator|UnitGenerateOptions.Comparable|UnitGenerateOptions.MinMaxMethod)]publicreadonlypartialstructStrength{}[UnitOf(typeof(DateTime),UnitGenerateOptions.Validate|UnitGenerateOptions.ParseMethod|UnitGenerateOptions.Comparable)]publicreadonlypartialstructEndDate{}[UnitOf(typeof(double),UnitGenerateOptions.ParseMethod|UnitGenerateOptions.MinMaxMethod|UnitGenerateOptions.ArithmeticOperator|UnitGenerateOptions.ValueArithmeticOperator|UnitGenerateOptions.Comparable|UnitGenerateOptions.Validate|UnitGenerateOptions.JsonConverter|UnitGenerateOptions.MessagePackFormatter|UnitGenerateOptions.DapperTypeHandler|UnitGenerateOptions.EntityFrameworkValueConverter)]publicreadonlypartialstructAllOptionsStruct{}You can setup project default options like this.
internalstaticclassUnitOfOptions{publicconstUnitGenerateOptionsDefault=UnitGenerateOptions.ArithmeticOperator|UnitGenerateOptions.ValueArithmeticOperator|UnitGenerateOptions.Comparable|UnitGenerateOptions.MinMaxMethod;}[UnitOf(typeof(int),UnitOfOptions.Default)]publicreadonlypartialstructHp{}// Defaultpublicstaticexplicitoperator U(Tvalue)=>value.value;publicstaticexplicitoperator T(Uvalue)=>newT(value);// UnitGenerateOptions.ImplicitOperatorpublicstaticimplicitoperator U(Tvalue)=>value.value;publicstaticimplicitoperator T(Uvalue)=>newT(value);publicstaticTParse(strings)publicstaticboolTryParse(strings,outTresult)publicstaticTMin(Tx,Ty)publicstaticTMax(Tx,Ty)publicstaticToperator+(inTx,inTy)=>newT(checked((U)(x.value+y.value)));publicstaticToperator-(inTx,inTy)=>newT(checked((U)(x.value-y.value)));publicstaticToperator*(inTx,inTy)=>newT(checked((U)(x.value*y.value)));publicstaticToperator/(inTx,inTy)=>newT(checked((U)(x.value/y.value)));publicstaticToperator+(Tvalue)=>new((U)(+value.value));publicstaticToperator-(Tvalue)=>new((U)(-value.value));publicstaticToperator++(Tx)=>newT(checked((U)(x.value+1)));publicstaticToperator--(Tx)=>newT(checked((U)(x.value-1)));In addition, all members conforming to System.Numerics.INumber are generated.
If you want to suppress this and generate only certain operators, you can use the the ArithmeticOperatros option of [UnitOf] attribute as follows:
[UnitOf(typeof(int),UnitGenerateOptions.ArithmeticOperator,ArithmeticOperators=UnitArithmeticOperators.Addition|UnitArithmeticOperators.Subtraction)]publicreadonlypartialstructHp{}| Value | Generates |
|---|---|
| UnitArithmeticOperators.Addition | T operator +(T, T) |
| UnitArithmeticOperators.Subtraction | T operator -(T, T) |
| UnitArithmeticOperators.Multiply | T operator *(T, T), T operator +(T), T operator-(T) |
| UnitArithmeticOperators.Division | T operator /(T, T), T operator +(T), T operator-(T) |
| UnitArithmeticOperators.Increment | T operator ++(T) |
| UnitArithmeticOperators.Decrement | T operator --(T) |
publicstaticToperator+(inTx,inUy)=>newT(checked((U)(x.value+y)));publicstaticToperator-(inTx,inUy)=>newT(checked((U)(x.value-y)));publicstaticToperator*(inTx,inUy)=>newT(checked((U)(x.value*y)));publicstaticToperator/(inTx,inUy)=>newT(checked((U)(x.value/y)));Implements IComparable<T> and >, <, >=, <= operators.
publicUCompareTo(Tother)=>value.CompareTo(other.value);publicstaticbooloperator>(inTx,inTy)=>x.value>y.value;publicstaticbooloperator<(inTx,inTy)=>x.value<y.value;publicstaticbooloperator>=(inTx,inTy)=>x.value>=y.value;publicstaticbooloperator<=(inTx,inTy)=>x.value<=y.value;Without implements >, <, >=, <= operators. For example, useful for Guid.
[UnitOf(typeof(Guid),UnitGenerateOptions.Comparable|UnitGenerateOptions.WithoutComparisonOperator)]publicreadonlypartialstructFooId{}Implements partial void Validate() method that is called on constructor.
// You can implement this custom validate method.[UnitOf(typeof(int),UnitGenerateOptions.Validate)]publicreadonlypartialstructSampleValidate{// impl here.privatepartialvoidValidate(){if(value>9999)thrownewException("Invalid value range: "+value);}}// Source generator generate this codes.publicT(int value){this.value=value;this.Validate();}privatepartialvoidValidate();Implements partial void Normalize(ref T value) method that is called on constructor.
// You can implement this custom normalize method to change value during initialization[UnitOf(typeof(int),UnitGenerateOptions.Normalize)]publicreadonlypartialstructSampleValidate{// impl here.privatepartialvoidNormalize(refintvalue){value=Math.Max(value,9999);}}// Source generator generate this codes.publicT(int value){this.value=value;this.Normalize(refthis.value);}privatepartialvoidNormalize(refintvalue);Implements System.Text.Json's JsonConverter. It will be used JsonSerializer automatically.
[JsonConverter(typeof(UserIdJsonConverter))]publicreadonlypartialstructUserId{classUserIdJsonConverter:JsonConverter<UserId>}Implements JsonConverter's WriteAsPropertyName/ReadAsPropertyName. It supports from .NET 6, supports Dictionary's Key.
vardict=Dictionary<UserId,int>JsonSerializer.Serialize(dict);Implements MessagePack for C#'s MessagePackFormatter. It will be used MessagePackSerializer automatically.
[MessagePackFormatter(typeof(UserIdMessagePackFormatter))]publicreadonlypartialstructUserId{classUserIdMessagePackFormatter:IMessagePackFormatter<UserId>}Implements Dapper's TypeHandler by public accessibility. TypeHandler is automatically registered at the time of Module initialization.
publicreadonlypartialstructUserId{publicclassUserIdTypeHandler:Dapper.SqlMapper.TypeHandler<UserId>}[ModuleInitializer]
public staticvoid AddTypeHandler(){Dapper.SqlMapper.AddTypeHandler(new A.ATypeHandler());}Implements EntityFrameworkCore's ValueConverter by public accessibility. It is not registered automatically so you need to register manually.
publicreadonlypartialstructUserId{publicclassUserIdValueConverter:ValueConverter<UserId,int>}// setup handler manuallybuilder.HasConversion(newUserId.UserIdValueConverter());Minimum supported Unity version is 2022.3.12f1.
The easiest way is to install UnitGenerator from NuGet using NuGetForUnity.
Alternatively, you can download UnitGenerator.dll from the releases page page and set it up as a RoslynAnalyzer to make it work.
This library is under the MIT License.