Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Don't throw NRE when custom formatter returns null

  • Loading branch information...
commit f74872ab7f90ccb38f538eec418d4325dcc0e3ab 1 parent aa8ffef
@marek-safar marek-safar authored
View
22 mcs/class/corlib/System/String.cs
@@ -1953,6 +1953,8 @@ internal static StringBuilder FormatHelper (StringBuilder result, IFormatProvide
int ptr = 0;
int start = ptr;
+ var formatter = provider != null ? provider.GetFormat (typeof (ICustomFormatter)) as ICustomFormatter : null;
+
while (ptr < format.length) {
char c = format[ptr ++];
@@ -1981,21 +1983,21 @@ internal static StringBuilder FormatHelper (StringBuilder result, IFormatProvide
object arg = args[n];
string str;
- ICustomFormatter formatter = null;
- if (provider != null)
- formatter = provider.GetFormat (typeof (ICustomFormatter))
- as ICustomFormatter;
if (arg == null)
str = Empty;
else if (formatter != null)
str = formatter.Format (arg_format, arg, provider);
- else if (arg is IFormattable)
- str = ((IFormattable)arg).ToString (arg_format, provider);
else
- str = arg.ToString ();
+ str = null;
- // pad formatted string and append to result
+ if (str == null) {
+ if (arg is IFormattable)
+ str = ((IFormattable)arg).ToString (arg_format, provider);
+ else
+ str = arg.ToString ();
+ }
+ // pad formatted string and append to result
if (width > str.length) {
const char padchar = ' ';
int padlen = width - str.length;
@@ -2008,9 +2010,9 @@ internal static StringBuilder FormatHelper (StringBuilder result, IFormatProvide
result.Append (padchar, padlen);
result.Append (str);
}
- }
- else
+ } else {
result.Append (str);
+ }
start = ptr;
}
View
21 mcs/class/corlib/Test/System/StringTest.cs
@@ -24,6 +24,20 @@ namespace MonoTests.System
[TestFixture]
public class StringTest
{
+ class NullFormatter : IFormatProvider, ICustomFormatter
+ {
+ public string Format (string format, object arg, IFormatProvider provider)
+ {
+ return null;
+ }
+
+ public object GetFormat (Type formatType)
+ {
+ return this;
+ }
+ }
+
+
private CultureInfo orgCulture;
[SetUp]
@@ -1162,6 +1176,13 @@ public void Format5_Format_Null ()
}
[Test]
+ public void Format ()
+ {
+ var s = String.Format (new NullFormatter (), "{0:}", "test");
+ Assert.AreEqual ("test", s);
+ }
+
+ [Test]
public void TestGetEnumerator ()
{
string s1 = "original";
Please sign in to comment.
Something went wrong with that request. Please try again.