Skip to content

Pass correct parameterName to ArgumentException #33763

Description

@terrajobst

Find places where nameof(...) is passed as the first (rather than second) argument to ArgumentException. Also places where nameof is used as the argument name in an ArgumentException (or derived type) but where it's not referring to a parameter.

Category: Reliability Usage

Examples to detect:

Single-argument nameof (or a literal string that matches the name of a parameter). Fixer: change to call the two argument constructor, pass null for the first parameter.

publicvoidSomeMethod(stringformatted){if(!Helper.TryParse(arg,outParsedparsed)){thrownewArgumentException(nameof(formatted));}}

Two argument call, first one looks like the parameter. Flip the argument order.

publicvoidSomeMethod(stringformatted){if(!Helper.TryParse(arg,outParsedparsed)){thrownewArgumentException(nameof(formatted),string.Format(Resources.DidNotParse,formatted));}}

Two argument call, paramName is a literal, but not a parameter name. (No fixer, just squiggle the argument.)

publicvoidSomeMethod(stringformatted){if(!Helper.TryParse(arg,outParsedparsed)){thrownewArgumentException(string.Format(Resources.DidNotParse,formatted),"input");}}

Two argument call, paramName is a literal, but not nameof. (Fixer: use nameof)

publicvoidSomeMethod(stringformatted){if(!Helper.TryParse(arg,outParsedparsed)){thrownewArgumentException(string.Format(Resources.DidNotParse,formatted),"formatted");}}

Examples to not detect:

Probably wrong (based on the parameter names), but probably shouldn't warn; since we're kinda guessing.

publicstaticvoidThrowArgumentException(stringparam,stringmsg){thrownewArgumentException(param,msg);}

When the parameter name comes from a variable rather than a literal, don't squiggle.

publicstaticvoidThrowArgumentException(stringmsg,stringparam){thrownewArgumentException(msg,param);}
publicvoidSomeMethod(stringformatted,intidx){stringargFail=null;stringmsg=null;if(!Helper.TryParse(arg,outParsedparsed)){argFail="formatted";msg=string.Format(Resources.DidNotParse,formatted);}elseif(parsed.Length<idx){// Disregard that ArgumentOutOfRangeException is better here.argFail="idx";msg=string.Format(Resources.OutOfRange,idx,parsed.Length);}if(argFail!=null){thrownewArgumentException(msg,argFail);}}

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Runtimecode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions