-
Notifications
You must be signed in to change notification settings - Fork 413
add GetRequiredValue to avoid null checks for required options #2564
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
cc @jaredpar - weren't we jsut talking about some nullability analysis for this use method? |
| } | ||
|
|
||
| [Fact] | ||
| public void GetRequiredValue_throws_when_argument_without_default_value_was_not_provided() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are we also testing Option.GetRequiredValue for these cases?
| } | ||
|
|
||
| [Fact] | ||
| public void GetRequiredValue_throws_when_argument_without_default_value_was_not_provided() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ParserTests is a bit of a catchall. I think these would be better organized under ArgumentTests and OptionTests.
| => GetResult(name) switch | ||
| { | ||
| OptionResult optionResult => optionResult.GetValueOrDefault<T>(), | ||
| ArgumentResult argumentResult => argumentResult.GetValueOrDefault<T>(), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe this can still return null.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe this can still return
null.
The only scenario I can come up with is the user defining null as the default value via DefaultValueFactory. Do you believe we should throw in such cases?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My memory was that SymbolResult.GetResult would never return null but either I misremembered or that changed at some point. This looks great!
Yes. It's the number one cause of nullable suppressions in sdk after I changed the opt in model. |
The existing
GetValuemethod returns nullableT?, which often leads to plenty of nullability warnings when working with required options.GetRequiredValuereturns the parsed (or configured default value) or throws.Option<FileInfo> fileOption = new("--file") { Required = true }; RootCommand command = new() { fileOption }; command.SetAction(paseResult => { - FileInfo file = paseResult.GetValue(fileOption)!; // mind the ! + FileInfo file = paseResult.GetRequiredValue(fileOption); Console.WriteLine($"File name: {file.FullName}"); });