Last active
April 11, 2017 03:34
-
-
Save Porges/0ff95ac3d066e108cb164636fa92ac7c to your computer and use it in GitHub Desktop.
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
| void Main() | |
| { | |
| AssertNullChecked(() => new List<int>(null)); | |
| } | |
| public static void AssertNullChecked(Expression<Action> expr) | |
| { | |
| (IReadOnlyCollection<Expression>, IReadOnlyCollection<ParameterInfo>) GetArgumentsAndParameters() | |
| { | |
| if (expr.Body is MethodCallExpression callExp) | |
| { | |
| return (callExp.Arguments, callExp.Method.GetParameters()); | |
| } | |
| if (expr.Body is NewExpression newExp) | |
| { | |
| return (newExp.Arguments, newExp.Constructor.GetParameters()); | |
| } | |
| throw new NotSupportedException($"Unsupported expression type: {expr.Body.GetType()}"); | |
| } | |
| var (args, parameters) = GetArgumentsAndParameters(); | |
| var (_, nullParameter) = | |
| args.Zip(parameters, (arg, param) => (arg, param)) | |
| .Single(x => x.Item1 is ConstantExpression constant && constant.Value == null); | |
| var ex = Assert.Throws<ArgumentNullException>(expr.Compile()); | |
| Assert.Equal(ex.ParamName, nullParameter.Name); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment