I came across the fact that an array of strings initialized with “null” elements when checking an element for “null” can return FALSE depending on the syntax of the code.
For example:
new string[] { null }[0] == null
as well as
new string[] { null }[0] is null
will return False
But:
new string[] { null }[0] == null ? true : false
as well as
new string[] { null }[0] is null ? true : false
will return True
When creating a string array in the debugger, we may see "" (empty) values when they should be null.
When you explicitly set the value null for an element after creating an array, this uncertainty disappears and the debugger displays a null value. And the comparison also works correctly.
If this behavior is not a bug, then please write about this feature in the documentation.
Code:
using System.Diagnostics;
namespace ArrayString
{
internal class Program
{
static void Main()
{
string[] snArr = new string[] { null };
string[] seArr = new string[] { string.Empty };
Check(nameof(snArr) + "[0]", snArr[0]);
snArr[0] = null;
Check(nameof(snArr) + "[0]", snArr[0]);
snArr[0] = string.Empty;
Check(nameof(snArr) + "[0]", snArr[0]);
Check(nameof(seArr) + "[0]", seArr[0]);
seArr[0] = null;
Check(nameof(seArr) + "[0]", seArr[0]);
seArr[0] = string.Empty;
Check(nameof(seArr) + "[0]", seArr[0]);
}
private static void Write(string msg) => Debug.WriteLine(msg);
private static void Write(string msg, bool isNull) => Write($"{$"\"{msg}\"",-40} {isNull}");
private static void Check(string valueName, string obj)
{
Write($"{valueName} == null", obj == null);
Write($"{valueName} is null", obj is null);
Write($"{valueName} == null ? true : false", obj == null ? true : false);
Write($"{valueName} is null ? true : false", obj is null ? true : false);
Write("");
}
}
}