Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active April 11, 2017 03:34
Show Gist options
  • Select an option

  • Save Porges/0ff95ac3d066e108cb164636fa92ac7c to your computer and use it in GitHub Desktop.

Select an option

Save Porges/0ff95ac3d066e108cb164636fa92ac7c to your computer and use it in GitHub Desktop.
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