0 out of 1 rated this helpful - Rate this topic

CA2241: Provide correct arguments to formatting methods

TypeName

ProvideCorrectArgumentsToFormattingMethods

CheckId

CA2241

Category

Microsoft.Usage

Breaking Change

Non Breaking

The format string argument passed to a method such as WriteLine, Write, or String.Format does not contain a format item that corresponds to each object argument, or vice versa.

The arguments to methods such as WriteLine, Write, and Format consist of a format string followed by several System.Object instances. The format string consists of text and embedded format items of the form, {index[,alignment][:formatString]}. 'index' is a zero-based integer that indicates which of the objects to format. If an object does not have a corresponding index in the format string, the object is ignored. If the object specified by 'index' does not exist, a System.FormatException is thrown at runtime.

To fix a violation of this rule, provide a format item for each object argument and provide an object argument for each format item.

Do not suppress a warning from this rule.

The following example shows two violations of the rule.


using System;

namespace UsageLibrary
{
   class CallsStringFormat
   {
      void CallFormat()
      {
         string file = "file name";
         int errors = 13;

         // Violates the rule.
         Console.WriteLine(string.Format("{0}", file, errors));

         Console.WriteLine(string.Format("{0}: {1}", file, errors));

         // Violates the rule and generates a FormatException at runtime.
         Console.WriteLine(string.Format("{0}: {1}, {2}", file, errors));
      }
   }
}


Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Disagreeing with Code Analysis Rules
The MSDN Library community content is designed primarily to enable MSDN users to provide extensions and explanations of the documentation. To discuss the implementation of code analysis rules, post your questions or opinions on the Visual Studio Code Analysis and Code Metrics forum (http://social.msdn.microsoft.com/Forums/en-US/vstscode/). To provide feedback directly to the development team, you can file a bug on the Connect site for Visual Studio 2010 and .NET Framework 4 (https://connect.microsoft.com/VisualStudio).
Abusive CA2241
The following seems to fire CA2241 but should not:
string result = String.Format("{0}{1}-{0}{2}", a, b, c);    // four {}, but three values