When I was looking at String.Join method implementation, I saw a for loop like this:
public static string Join(string separator, params object[] values)
{
...
for (int index = 1; index < values.Length; ++index)
{
sb.Append(separator);
if (values[index] != null) // first if statement
{
string str2 = values[index].ToString();
if (str2 != null) // second if statement
sb.Append(str2);
}
}
...
}
Here, second if statement seems redundant to me.I thought if values[index] != null is true then how could be values[index].ToString() == null true ? As far as I know ToString always has to be return something, right ? Even if the type doesn't override ToString method it should return Type's fully qualified name (Namespace + Class name).So when I see it in .NET Framework source code, I thought maybe there is a reason and I'm missing something.If there is a reason, what is it ?
Technically it’s not redundant, as it’s possible that an object’s ToString implementation returns null. Of course that’s not really useful and custom types shouldn’t do that.
Practically in your case however, the check is redundant because StringBuilder is fine when the argument to Append is null. It will then just append nothing:
StringBuilder sb = new StringBuilder("A");
sb.Append((string) null);
sb.Append("B");
Console.WriteLine(sb.ToString() == "AB"); // true
I suppose you could override ToString and return null.
public override string ToString()
{
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With