Skip to content

Commit fc8c2c0

Browse files
authored
Fix null parms in String.Format (#144)
1 parent 1d7f1e8 commit fc8c2c0

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

Tests/NFUnitTestSystemLib/UnitTestStringTests.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,28 @@ public void Concat_Test1()
315315
string str = "a" + 1 + "b" + new ToStringReturnsNull();
316316
Assert.Equal(str, "a1b");
317317
}
318+
319+
[TestMethod]
320+
public void Format()
321+
{
322+
Assert.Equal(String.Format("The value is {0}", 32), "The value is 32",
323+
"String.Format with a single variable");
324+
Assert.Equal(String.Format("The value with formatter is {0:d3}", 32), "The value with formatter is 032",
325+
"String.Format with a decimal formatter.");
326+
}
327+
328+
[TestMethod]
329+
public void FormatWithNull()
330+
{
331+
object nullObject = null;
332+
Assert.Equal(String.Format("The value is {0}", nullObject), "The value is ",
333+
"String.Format should treat a null argument as an empty string");
334+
Assert.Equal(String.Format("The value with formatter is {0:d}", nullObject), "The value with formatter is ",
335+
"String.Format should treat a null argument as an empty string when used with formatters.");
336+
Assert.Equal(String.Format("First parm: '{0}' second parm: '{1}'", new object[] { nullObject, 32 }), "First parm: '' second parm: '32'",
337+
"Formatting with two parms should also work");
338+
Assert.Equal($"the value is {nullObject}", "the value is ", "Interpolated strings should use string.format and work correctly");
339+
}
318340
}
319341

320342
/// <summary>

nanoFramework.CoreLibrary/System/String.cs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -709,18 +709,26 @@ public static string Format(string format, params object[] args)
709709
if (fmt.Length > 0)
710710
{
711711
#if NANOCLR_REFLECTION
712-
var method = args[index].GetType().GetMethod("ToString", new Type[] { typeof(string) });
713-
token = (method is null)
714-
? args[index].ToString()
715-
: method.Invoke(args[index], new object[] { token }).ToString();
712+
713+
if (args[index] is null)
714+
{
715+
token = "";
716+
}
717+
else
718+
{
719+
var method = args[index].GetType().GetMethod("ToString", new Type[] { typeof(string) });
720+
token = (method is null)
721+
? args[index].ToString()
722+
: method.Invoke(args[index], new object[] { token }).ToString();
723+
}
716724
#else
717725
throw new NotImplementedException();
718726
#endif // NANOCLR_REFLECTION
719727

720728
}
721729
else
722730
{
723-
token = args[index].ToString();
731+
token = args[index] == null ? "" : args[index].ToString();
724732
}
725733

726734
if (alignment > 0)

0 commit comments

Comments
 (0)