V3165. The expression of the 'char' type is passed as an argument of the 'A' type whereas similar overload with the string parameter exists.
The analyzer detected a possible error when calling the constructor or method. An expression of 'char' type which is implicitly converted to another type is used as one of the arguments. While a suitable overload is found, in which the corresponding parameter is represented by the 'String' type. It may have been necessary to use an expression of type 'String' instead of 'char' to call the correct overload.
Consider an example:
public static string ToString(object[] a)
{
StringBuilder sb = new StringBuilder('['); // <=
if (a.Length > 0)
{
sb.Append(a[0]);
for (int index = 1; index < a.Length; ++index)
{
sb.Append(", ").Append(a[index]);
}
}
sb.Append(']');
return sb.ToString();
}
The developer wanted the string stored in the instance of the 'StringBuilder' type to start with a square bracket. However, due to a typo, an object without any characters with a capacity of 91 elements, will be created.
This happened because a single quotation mark was used instead of double ones, which led to the wrong constructor overload call:
....
public StringBuilder(int capacity);
public StringBuilder(string? value);
....
When the constructor is called, the character literal '[' will be implicitly cast to the corresponding value of 'int' type (91 in Unicode). Thereby the constructor with an 'int' parameter setting the initial capacity will be called instead of the constructor setting the string's beginning.
To fix the error, replace the character literal with a string literal, which will allow calling the correct constructor overload:
public static string ToString(object[] a)
{
StringBuilder sb = new StringBuilder("[");
....
}
This diagnostic rule takes into account not only literals, but also expressions, so the following code will also trigger a warning:
public static string ToString(object[] a)
{
var initSmb = '[';
StringBuilder sb = new StringBuilder(initSmb);
....
}
This diagnostic is classified as: