Skip to content

[Feature]: A way to normalize parsed values #969

Description

@aradalvand

Describe the feature

Consider this value object, whose string representation is customized to include a prefix (e.g. E1, E12, etc.).

[ValueObject<int>]
public readonly partial struct AggregateEdition : IEdition<AggregateEdition>, IValueObject<AggregateEdition, int>
{
	// NOTE: This is how to customize a Vogen value object's string representation — see https://github.com/SteveDunn/Vogen/pull/791/changes#diff-478e2c1cf89c8927b9cc135dffa8eceefb9473e374b46323fa2834a194eb3760R79
	public override string ToString() =>
		$"E{Value}";

	bool ISpanFormattable.TryFormat(
		Span<char> destination,
		out int charsWritten,
		ReadOnlySpan<char> format,
		IFormatProvider? provider
	)
	{
		if (!IsInitialized())
		{
			charsWritten = default;
			return false;
		}
		return destination.TryWrite($"E{Value}", out charsWritten);
	}
}

When these string representations, however, are parsed using AggregateEdition.TryParse, the parsing fails because the Parse/TryParse methods that Vogen generates simply forward the call to the underlying type's Parse/TryParse method(s) — and of course, int.TryParse("E12", out ...) is false.

I propose a second normalization method next to NormalizeInput(TUnderlyingType input) (the name is open to bikeshedding):

[ValueObject<int>]
public readonly partial struct AggregateEdition : IEdition<AggregateEdition>, IValueObject<AggregateEdition, int>
{
	// ...
   	private static string NormalizeParsed(string inputToParse) =>
		inputToParse.TrimStart('E');
}

The Vogen-generated Parse/TryParse implementations then simply invoke this method and feed its return value to the underlying type's Parse/TryParse — e.g. int.TryParse(NormalizeParsed("E12"), out ...) is true.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions