Last active
January 18, 2022 16:21
-
-
Save alastairs/ab284c651709cc98eedf222d9e22e7e3 to your computer and use it in GitHub Desktop.
Using C# pattern matching for string argument checks
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
// 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 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
// 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