Skip to content

Instantly share code, notes, and snippets.

@solrevdev
Last active June 26, 2023 20:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
A Money value object class/record and a generic result class/record wrapper to return it
public record Money
{
private static readonly IReadOnlyCollection<string> SupportedCurrencies = new[] { "GBP", "EUR" };
public decimal Amount { get; }
public string Currency { get; }
private Money(decimal amount, string currency)
{
Amount = amount;
Currency = currency;
}
public static Result<Money> Create(decimal amount, string currency)
{
if (string.IsNullOrWhiteSpace(currency))
{
return Result<Money>.Failure($"{nameof(currency)} cannot be null or whitespace.");
}
if (!SupportedCurrencies.Contains(currency.ToUpperInvariant()))
{
return Result<Money>.Failure($"'{currency}' is not supported.");
}
return Result<Money>.Success(new(amount, currency));
}
}
public record Result<T>
{
public bool IsSuccess { get; private init; }
public T? Value { get; private init; }
public string? ErrorMessage { get; private init; }
private Result() { }
public static Result<T> Success(T value) => new() { IsSuccess = true, Value = value };
public static Result<T> Failure(string errorMessage) => new()
{
IsSuccess = false,
ErrorMessage = errorMessage
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment