strings are immutable classes, fine
but consider the Trim function. What happens when Trim finds out theres nothing to trim. Will it do just "return this" or "return new string(this)"
??
Printable View
strings are immutable classes, fine
but consider the Trim function. What happens when Trim finds out theres nothing to trim. Will it do just "return this" or "return new string(this)"
??
nvm, the following code prints true for s1 = "test" and false for "test "
Code:string s1 = "test";
string s2 = s1.Trim();
Console.WriteLine(object.ReferenceEquals(s1, s2));
You can always decompile the string.Trim() method to find out also:
You can see that if the length doesn't change it just returns itself.Code:public string Trim()
{
return this.TrimHelper(2);
}
private string TrimHelper(int trimType)
{
int num = this.Length - 1;
int num2 = 0;
if (trimType != 1)
{
num2 = 0;
while (num2 < this.Length && char.IsWhiteSpace(this[num2]))
{
num2++;
}
}
if (trimType != 0)
{
num = this.Length - 1;
while (num >= num2 && char.IsWhiteSpace(this[num]))
{
num--;
}
}
return this.CreateTrimmedString(num2, num);
}
private string CreateTrimmedString(int start, int end)
{
int num = end - start + 1;
if (num == this.Length)
{
return this;
}
if (num == 0)
{
return string.Empty;
}
return this.InternalSubString(start, num, false);
}