Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this if statement redundant or not?

Tags:

string

c#

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 ?

like image 976
Selman Genç Avatar asked Jan 15 '14 22:01

Selman Genç


2 Answers

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
like image 179
poke Avatar answered Sep 23 '22 12:09

poke


I suppose you could override ToString and return null.

public override string ToString()
{
    return null;
}
like image 30
Kevin DiTraglia Avatar answered Sep 26 '22 12:09

Kevin DiTraglia