SteveDunn / Vogen

A semi-opinionated library which is a source generator and a code analyser. It Source generates Value Objects
Apache License 2.0
734 stars 41 forks source link

Suggestion - DefaultValue #599

Open Aragas opened 1 month ago

Aragas commented 1 month ago

Describe the feature

In my real life scenarios I have a concept of DefaultValue - it's mostly used in my custom TryParse scenarios, when the parsing failed, but the value still needs to be valid an initialized with something meaningful.
A possible implementation would be to have a static property DefaultValue, this way we also should be able to use with Static Abstract Members if needed for custom solutions.
The only note I have, since not every type has a default value, it would make sense to have a separate interface IVogenHasDefaultValue<>


[ValueObject<byte>]
[Instance("None", "0")]
public readonly partial record struct TenantId
{
    // Either manually or via Instance
    //public static readonly byte None = From(0);

    public static byte DefaultValue => None;
    // ...
    // Generated Code
    public static global::System.Boolean TryParse(global::System.ReadOnlySpan<byte> utf8Text, 
#if NETCOREAPP3_0_OR_GREATER
[global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)]
#endif
 out TenantId result) {
        if(System.Byte.TryParse(utf8Text, out var __v)) {

            result = new TenantId(__v);
            return true;
        }

        result = DefaultValue; // instead of `= default`;
        return false;
    }
}