Text - NKS0001

Use TextTools.FormatString() instead of string.Format()

This analyzer provides the following strings:

Context
String

Error List

Caller uses string.Format() instead of TextTools.FormatString()

Suggestion Box

Use TextTools.FormatString() instead of string.Format()

Description

TextTools.FormatString() uses the error handler to handle unknown formatting errors and returns the unformatted string if such errors happen, but string.Format() immediately throws.

Extended Description

This code analyzer detects the usage of the standard string.Format() method from the regular .NET core libraries, and highlights the relevant parts as yellow squiggly lines indicating a warning.

The reason is that string.Format() tries to format any text within the .NET string formatting syntax defined in this link, and throws an exception if any of these syntaxes are invalid. However, TextTools.FormatString() is clever at handling such exceptions and returns the unformatted string in case formatting fails.

Also, TextTools.FormatString() doesn't attempt to format any string and returns the plain string that's passed to it if there are no arguments to be passed to the formatter, making it impossible to crash if it was used without arguments accidentally or intentionally.

This analyzer detects the usage of string.Format() and fixes it by replacing the call with TextTools.FormatString(), importing the Textify.General namespace if necessary.

Analysis Comparison

To get a brief insight about how this analyzer works, compare the two code blocks shown to you below:

Before the fix

Somewhere in your mod code...
public static void MyFunction() =>
    TextWriterColor.Write(string.Format("Hello, {0}!", "Nitrocid"));

After the fix

Somewhere in your mod code...
public static void MyFunction() =>
    TextWriterColor.Write(TextTools.FormatString("Hello, {0}!", "Nitrocid"));

Suppression

You can suppress this warning by including it in the appropriate place, whichever is convenient.

For more information about how to suppress any warning issued by the Nitrocid analyzer, visit the below page:

Recommendation

We recommend that every caller which use the string.Format() method use the recommended abovementioned method.

Last updated