2
Reply

Casting and TrimEnd

Maha

Maha

Jan 23 2014 10:34 AM
957
http://www.dotnetperls.com/string-join

Following program is given in the above website. Please explain the reasons for the followings:

-In order to cast builder why it is not correct to use (string)builder.

-TrimEnd({ ',' }) is doing the job instead of TrimEnd(new char[] { ',' })

Problem is highlited.

using System;
using System.Text;

class Program
{
static void Main()
{
string[] catSpecies = { "Aegean", "Birman", "Main Coon", "Nebulung" };
Console.WriteLine(CombineA(catSpecies));
Console.WriteLine(CombineB(catSpecies));

Console.Read();
}

/// <summary>
/// Combine strings with commas.
/// </summary>
static string CombineA(string[] arr)
{
return string.Join(",", arr);
}

/// <summary>
/// Combine strings with commas.
/// </summary>
static string CombineB(string[] arr)
{
StringBuilder builder = new StringBuilder();

foreach (string s in arr)
{
builder.Append(s).Append(",");
}
return builder.ToString().TrimEnd(new char[] { ',' });
}
}
/*
Aegean,Birman,Main Coon,Nebulung
Aegean,Birman,Main Coon,Nebulung
*/


Answers (2)