A lightweight and elegant Result Pattern implementation for handling success and failure scenarios in C#.
TeymurDevv.ResultPattern is a simple yet powerful library that provides a structured way to handle operations that can either succeed or fail, reducing reliance on exceptions and improving code clarity.
- Encapsulates success and failure outcomes in a single result type.
- Eliminates excessive
if-elsechecks. - Improves readability and maintainability of business logic.
- Avoids using exceptions for expected errors.
- Works seamlessly with ASP.NET Core, CQRS, and MediatR.
Install via NuGet Package Manager:
Install-Package TeymurDevv.ResultPatternOr via .NET CLI:
dotnet add package TeymurDevv.ResultPatternusing TeymurDevv.ResultPattern;
var successResult = Result<string>.Success("Operation successful");
Console.WriteLine(successResult.Value); // Output: Operation successful
var failureResult = Result<string>.Failure("Something went wrong");
Console.WriteLine(failureResult.Error); // Output: Something went wrongvar operationResult = Result.Success();
if (operationResult.IsSuccess)
{
Console.WriteLine("Operation succeeded");
}
else
{
Console.WriteLine($"Error: {operationResult.Error}");
}public class UserService
{
public Result<User> GetUserById(int id)
{
var user = _userRepository.GetById(id);
if (user == null)
{
return Result<User>.Failure("User not found");
}
return Result<User>.Success(user);
}
}[ApiController]
[Route("api/users")]
public class UserController : ControllerBase
{
private readonly UserService _userService;
public UserController(UserService userService)
{
_userService = userService;
}
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var result = _userService.GetUserById(id);
if (result.IsFailure)
return NotFound(new { message = result.Error });
return Ok(result.Value);
}
}✅ Explicit error handling – No more guessing where exceptions might occur.
✅ Improves performance – Avoids costly exceptions for expected failures.
✅ Increases maintainability – Cleaner and more structured error handling.
✅ Works with CQRS & MediatR – Perfect for modern backend architectures.
- Add logging integration
- Extend support for
Result<T>chaining - Improve compatibility with LINQ expressions
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Feel free to submit issues, feature requests, or pull requests on GitHub.
If you find this package useful, please ⭐ it on GitHub! 😊