Result
Result copied to clipboard
Implicit operator from Result<T> to Result<U>
Hi
I would be interested in having an implicit operator from Result<T> to Result<U> just to maintain the state of internal properties.
I have a method that can return a Result<int> on success:
protected virtual async Task<Result<int>> SaveChangesReturnResultAsync()
{
try
{
var numberOfWritings = await Context.SaveChangesAsync();
return Result.Success(numberOfWritings);
}
catch (Exception ex)
{
if (ex.IsEntityAlreadyExistsException())
return Result.Conflict("Entity Already Exists");
if (ex.IsForeignKeyViolation())
return Result.Conflict("Foreign Key Violation");
throw;
}
}
But the caller must be able to return a Result<Tentity> if successful or propogate errors from the previous call:
public virtual async Task<Result<TEntity>> CreateAndReturnResultAsync(TEntity entity)
{
await Context.AddAsync(entity);
var result = await SaveChangesReturnResultAsync();
if (!result.IsSuccess)
return result; // Conversion error
return Result.Success(entity);
}
Currently what I have been able to obtain from the code base is a new implicit operator:
public static implicit operator Result(Result<T> result) => new()
{
Status = result.Status,
Errors = result.Errors,
SuccessMessage = result.SuccessMessage,
CorrelationId = result.CorrelationId,
ValidationErrors = result.ValidationErrors,
};
But this fix would force you to perform two conversion steps:
public virtual async Task<Result<TEntity>> CreateAndReturnResultAsync(TEntity entity)
{
await Context.AddAsync(entity);
var result = await SaveChangesReturnResultAsync();
Result temp = result; // From Result<int> to Result, to me it's ok to lost the original value.
if (!result.IsSuccess)
return temp; // Conversion ok
return Result.Success(entity);
}
Thanks in advance