Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
Ignacio Soler Garcia Avatar asked Apr 11 '26 03:04

Ignacio Soler Garcia


1 Answers

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.

like image 176
Jon Skeet Avatar answered Apr 13 '26 15:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!