Why string.Format does not throw ArgumentNullException?

According to MSDN String.Format throws if format is null (pretty reasonable), link here.

But testing says it only does that if the second argument is null as well, not if the second one is populated.

The following does not throw:

string test = string.Format(null, "string");

The following throws complaining about the first parameter (format):

string test = string.Format(null, null);

Digging futher with JustDecompile the source code calls the following method:

 private static string FormatHelper(IFormatProvider provider, string format, ParamsArray args)
 {
    if (format == null)
    {
        throw new ArgumentNullException("format");
    }
    return StringBuilderCache.GetStringAndRelease(StringBuilderCache.Acquire(format.Length + args.Length * 8).AppendFormatHelper(provider, format, args));
 }

Which makes no sense as format is null and no exception is thrown. Any hints?

Jon Skeet
people
quotationmark

Ah, the joys of overload resolution. In that case, you're actually calling string.Format(IFormatProvider, string, params object[]) - so you're passing a null argument for the provider parameter, which is entirely valid (and means to use the current culture).

That overload is "better" because the conversion of the second argument from string literal to string is better than the conversion from string literal to object.

If you use argument names to force the right overload, load this:

string text = string.Format(format: null, arg0: "string");

... then it throws an exception as expected.

people

See more on this question at Stackoverflow