Writing new guards with extensions in C# 14 #137
Replies: 2 comments 2 replies
-
|
How this is different from public static void ThrowIfHasOneCharacter(this ArgumentException ex , string argument, [CallerArgumentExpression("argument")] string? paramName = null)
{
if (argument.Length == 1)
{
throw new ArgumentException($"Argument '{paramName}' has exactly one character but shouldn't have.", paramName);
}
}? |
Beta Was this translation helpful? Give feedback.
-
|
The new extension capabilities seem great but haven't used them yet, can they be enabled in 9.0 with langversion? As a matter of taste though, I much prefer a single API for guards like CommunityToolkit.Diagnostics.Guard as I can start typing Guard and then see all the available options pop-up. Having to write out the full exception name, then the method and argument are a bridge to narrow & far. Possibly even better (depending on taste) would be arg.NotNull() which I use a lot to remove nullable warnings inline. Follows a very easy neural pathway from "I need to make sure" arg "is" NotNull() as opposed to "what is the name of that exception? Oh yeah, then which method? Ok now type the argument". |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Writing new guards with extensions in C# 14
In C# we have many nice guards sitting on top of static exceptions classes like ArgumentNullException, ArgumentOutOfRangeException, etc: As ArgumentException.ThrowIfNullOrEmpty, ArgumentException.ThrowIfNullOrWhiteSpace. Now we can extend them easily!
https://steven-giesel.com/blogPost/e2552b7a-293a-4f46-892f-95a0cd677e4d?utm_source=paulo+morgado&utm_medium=linkedin
Beta Was this translation helpful? Give feedback.
All reactions