Skip to content

Instantly share code, notes, and snippets.

@alastairs
Last active January 18, 2022 16:21
Show Gist options
  • Save alastairs/ab284c651709cc98eedf222d9e22e7e3 to your computer and use it in GitHub Desktop.
Save alastairs/ab284c651709cc98eedf222d9e22e7e3 to your computer and use it in GitHub Desktop.
Using C# pattern matching for string argument checks
// I think it would be nice to be able to use a `bool` Method Group in pattern matching statements, like
// string.IsNullOrWhitespace(). Here's an example.
public class Thing
{
private readonly IOptions<MyOptions> _options;
public Thing(IOptions<MyOptions> options)
{
_options = options switch
{
null => throw new ArgumentNullException(nameof(options)),
{ Value.Prop1: string.IsNullOrWhitespace } => throw new ArgumentNullException(nameof(options.Value.Prop1)),
{ Value.Prop2: string.IsNullOrWhitespace } => throw new ArgumentNullException(nameof(options.Value.Prop2)),
{ Value.Prop3: string.IsNullOrWhitespace } => throw new ArgumentNullException(nameof(options.Value.Prop3)),
_ => options
};
}
}
// This is what I ended up with! It's more verbose than I'd like, but 🤷🏻‍♂️
#nullable enable
public class Thing
{
private readonly IOptions<MyOptions> _options;
public Thing(IOptions<MyOptions> options)
{
_options = options switch
{
{ Value.Prop1: var prop }
when string.IsNullOrWhitespace(prop) =>
throw new ArgumentNullException(nameof(options.Value.Prop1)),
{ Value.Prop2: var prop }
when string.IsNullOrWhitespace(prop) =>
throw new ArgumentNullException(nameof(options.Value.Prop2))
{ Value.Prop3: var prop }
when string.IsNullOrWhitespace(prop) =>
throw new ArgumentNullException(nameof(options.Value.Prop3))
_ => options
};
}
}
#nullable restore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment