Last active
March 19, 2024 16:57
-
-
Save eocron/6cca9530005804c939ed3cefde8eca0d to your computer and use it in GitHub Desktop.
How validation can be done Fully-Coolly
This file contains 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
public class Program | |
{ | |
public static async Task Main() | |
{ | |
var results = Validate.If(() => "a" == "a") | |
//optional then branch | |
.Then(()=> | |
{ | |
Console.WriteLine("a equals a, so Then was executed"); | |
//some code | |
return Validate.If(() => "b" != "b") | |
.WithMessage("b not equals b"); | |
}) | |
//optional else branch | |
.Else(ElseBranch) | |
.WithMessage("a not equals a") | |
//optional as warning | |
.AsWarning(); | |
//as multiple errors | |
Console.WriteLine(string.Join(";", results.Select(x=> $"{x.Type}:{x.Message}"))); | |
//as single error (implicit cast) | |
ValidationResult vr = results; | |
Console.WriteLine($"{vr.Type}:{vr.Message}"); | |
} | |
private static IEnumerable<ValidationResult> ElseBranch() | |
{ | |
Console.WriteLine("a not equals a, so Else was executed"); | |
for (int i = 0; i < 10; i++) | |
{ | |
yield return Validate.If(() => "c" == "c") | |
.WithMessage("c not equals c"); | |
} | |
} | |
} | |
//###########OUTPUT########### | |
//a equals a, so Then was executed | |
//Error:b not equals b | |
//a equals a, so Then was executed | |
//Error:b not equals b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment