Skip to content

Instantly share code, notes, and snippets.

@pedroinfo
Last active February 3, 2025 20:36
Show Gist options
  • Save pedroinfo/d3b07c511bfd24b5ca54ef484916020b to your computer and use it in GitHub Desktop.
Save pedroinfo/d3b07c511bfd24b5ca54ef484916020b to your computer and use it in GitHub Desktop.
public class Result<T>
{
public T Value { get; }
public string Error { get; }
public bool IsSuccess => Error == null;
private Result(T value, string error)
{
Value = value;
Error = error;
}
public static Result<T> Success(T value) => new(value, null);
public static Result<T> Failure(string error) => new(default, error);
}
[ApiController]
[Route("api/users")]
public class UserController : ControllerBase
{
private static readonly Dictionary<int, string> Users = new()
{
{ 1, "Alice" },
{ 2, "Bob" }
};
[HttpGet("{id}")]
public ActionResult<Result<string>> GetUser(int id)
{
var result = GetUserById(id);
if (!result.IsSuccess)
{
return BadRequest(result);
}
return Ok(result);
}
private Result<string> GetUserById(int id)
{
if (Users.TryGetValue(id, out var user))
{
return Result<string>.Success(user);
}
return Result<string>.Failure("User not found.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment