rspec/rules/S2275/csharp/rule.adoc

43 lines
1.7 KiB
Plaintext
Raw Normal View History

2020-12-23 14:59:06 +01:00
Because composite format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that lead to unexpected behaviors or runtime errors. This rule statically validates the good behavior of composite formats when calling the methods of ``String.Format``, ``StringBuilder.AppendFormat``, ``Console.Write``, ``Console.WriteLine``, ``TextWriter.Write``, ``TextWriter.WriteLine``, ``Debug.WriteLine(String,Object[])``, ``Trace.TraceError(String,Object[])``, ``Trace.TraceInformation(String,Object[])``, ``Trace.TraceWarning(String,Object[])`` and ``TraceSource.TraceInformation(String,Object[])``.
2020-06-30 12:48:07 +02:00
== Noncompliant Code Example
----
s = string.Format("[0}", arg0);
s = string.Format("{{0}", arg0);
s = string.Format("{0}}", arg0);
s = string.Format("{-1}", arg0);
s = string.Format("{0} {1}", arg0);
----
== Compliant Solution
----
s = string.Format("{0}", 42); // Compliant
s = string.Format("{0,10}", 42); // Compliant
s = string.Format("{0,-10}", 42); // Compliant
s = string.Format("{0:0000}", 42); // Compliant
s = string.Format("{2}-{0}-{1}", 1, 2, 3); // Compliant
s = string.Format("no format"); // Compliant
----
== Exceptions
2020-12-23 14:59:06 +01:00
* No issue is raised if the format string is not a ``const``.
2020-06-30 12:48:07 +02:00
----
var pattern = "{0} {1} {2}";
var res = string.Format(pattern, 1, 2); // Compliant, not const string are not recognized
----
2020-06-30 12:48:07 +02:00
* No issue is raised if the argument is not an inline creation array.
2020-06-30 12:48:07 +02:00
----
var array = new int[] {};
var res = string.Format("{0} {1}", array); // Compliant we don't know the size of the array
----
2020-12-23 14:59:06 +01:00
* This rule doesn't check whether the format specifier (defined after the ``:``) is actually valid.
2020-06-30 12:48:07 +02:00
include::../see.adoc[]