Created
July 30, 2025 17:19
-
-
Save cybergitt/142ea03d692d1abb0c0b995b20112bc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Program.cs (Console App) | |
| using System; | |
| using System.Threading.Tasks; | |
| namespace ResultPatternConsoleApp | |
| { | |
| class Program | |
| { | |
| static async Task Main(string[] args) | |
| { | |
| var service = new FileProcessor(); | |
| var result = await service.ProcessFileAsync("data.txt"); | |
| if (result.IsSuccess) | |
| { | |
| Console.WriteLine("File content:\n" + result.Value); | |
| } | |
| else | |
| { | |
| foreach (var error in result.Errors) | |
| { | |
| Console.WriteLine($"[ERROR] {error.Code}: {error.Message}"); | |
| } | |
| } | |
| } | |
| } | |
| public class FileProcessor | |
| { | |
| public async Task<Result<string>> ProcessFileAsync(string path) | |
| { | |
| if (!File.Exists(path)) | |
| return Result<string>.Failure(new Error("FileNotFound", $"File {path} does not exist.")); | |
| var content = await File.ReadAllTextAsync(path); | |
| return Result<string>.Success(content); | |
| } | |
| } | |
| public class Result<T> | |
| { | |
| public bool IsSuccess { get; } | |
| public T? Value { get; } | |
| public List<Error> Errors { get; } | |
| public static Result<T> Success(T value) => new(true, value, new List<Error>()); | |
| public static Result<T> Failure(params Error[] errors) => new(false, default, errors.ToList()); | |
| private Result(bool isSuccess, T? value, List<Error> errors) | |
| { | |
| IsSuccess = isSuccess; | |
| Value = value; | |
| Errors = errors; | |
| } | |
| } | |
| public record Error(string Code, string Message); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment