Ranjeet
Ranjeet

Reputation: 141

Need help in creating custom FxCop rule for string.Format(...)

Please tell me how to write FxCOP custom rule for the following "String.Format()" methods parameter validation.

1.string.Format(“{0}aaaa{1}bbb”, x); // {1} has no placeholder replacement

2.string.Format(“aaaa{1}bbb”, x); // {1} has no placeholder replacement. Inside the string literal it should’ve been {0} instead of {1}.

Regards,

Ranjeet.

Upvotes: 2

Views: 403

Answers (3)

Luke Girvin
Luke Girvin

Reputation: 13442

There was a rule to check for this in FxCop 1.35, CA2241 - Provide correct arguments to formatting methods. It was removed from FxCop 1.36 "due to removal of [the] data flow engine" according to this blog post.

The rule seems to have been reinstated for Code Analysis for Visual Studio 2010 (see Nicole Calinoiu's answer), but as I mentioned in a comment, Code Analyis is only available in the Premium and Ultimate editions.

So, if you want to check your assemblies for incorrect calls to String.Format, and you don't have Visual Studio 2010 Premium or Ultimate, you will need to use FxCop 1.35. I'm running FxCop 1.35 and FxCop 10.0 side-by-side on my Windows 7 box without any problems.

Upvotes: 3

Daniel Becroft
Daniel Becroft

Reputation: 716

From reading the string.Format() MSDN documentation, shouldn't both of these scenarios raise FormatException errors at runtime?

My understanding is that FxCop is not designed to valid code for runtime errors, but to analyse assemblies for potential security/performance/naming/etc issues and report on those. Runtime errors are beyond its capabilities.

Upvotes: 1

Nicole Calinoiu
Nicole Calinoiu

Reputation: 21002

Is there some particular reason that you want a custom rule for this? The ProvideCorrectArgumentsToFormattingMethods rule that ships with FxCop already verifies String.Format arguments.

Upvotes: 1

Related Questions