Search code examples
c#string-formatting.net-8.0

How to use the new CompositeFormat class from .NET 8.0?


I'm testing migrating a .NET 6.0 application to .NET 8.0, and the following piece of code now throws CA1863 "Use 'CompositeFormat'". But I don't know how.

private const string DUMP_DIALOGS_TITLE_FORMAT_STRING = "{0} Diagnostic Report";

public static string GetTitle(IProcess currentProcess)
{
    return string.Format(CultureInfo.InvariantCulture, DUMP_DIALOGS_TITLE_FORMAT_STRING, currentProcess.ProcessName);
}

The example given here is invalid, since the StaticField variable isn't initialized and I don't know what it should be.

If I change the code to

private static readonly CompositeFormat Format = CompositeFormat.Parse("{0} Diagnostic Report");

public static string GetTitle(IProcess currentProcess)
{
    return string.Format(CultureInfo.InvariantCulture, Format, currentProcess.ProcessName);
}

Visual Studio shows a warning that I'm not providing a parameter for the {0} argument, even though everything appears to work as expected (I'm not getting a runtime error with the new code). Is it just that VS code analysis isn't knowing about CompositeFormat yet or am I missing something?


Solution

  • Your implementation is just fine:

    private static readonly CompositeFormat Format = CompositeFormat.Parse("{0} Diagnostic Report");
    
    public static string GetTitle(IProcess currentProcess)
    {
        return string.Format(CultureInfo.InvariantCulture, Format, currentProcess.ProcessName);
    }
    

    The warning comes from ReSharper which currently has only basic support of .NET 8 features (see the .NET SDK support in JetBrains Rider doc.).

    Either install the EAP/RC version (link) which should have the issue fixed or disable the warning with comment for now:

    // ReSharper disable once FormatStringProblem
    private static readonly CompositeFormat Format = CompositeFormat.Parse("{0} Diagnostic Report");
    

    P.S.

    Created a PR for the docs to make example potentially more clear.