user3809278
user3809278

Reputation: 9

Why TrimStart is working only when i assign the text again back th the variable?

scrollerList = new List<string>(TextExtractor.newTextWithoutLinks);
scrollerText = string.Join(Environment.NewLine, scrollerList);
combindedString = string.Join(Environment.NewLine, newText);
scroller1.TextToScroll = scrollerText;
richTextBox1.Text = combindedString;
richTextBox1.Text = richTextBox1.Text.TrimStart();
richTextBox1.Refresh();

This is a working line:

richTextBox1.Text = richTextBox1.Text.TrimStart();

But if i'm doing:

richTextBox1.Text.TrimStart();

It's not working i mean dosen't make any changes.

Not that i'm getting any exceptions but a bit strange i need to assign twice to the richTextBox1 the text to delete the empty line at the top of the richTextBox1.

Upvotes: 0

Views: 164

Answers (3)

coolerfarmer
coolerfarmer

Reputation: 385

It generates a new string, which has nothing to do with the old one. You have to replace the existing one with the new one! So this is right:

richTextBox1.Text = richTextBox1.Text.TrimStart();

Upvotes: 0

Prescott
Prescott

Reputation: 7412

TrimStart() returns a new string with the values trimmed. It does not modify the original string:

From http://msdn.microsoft.com/en-us/library/system.string.trimstart(v=vs.110).aspx

This method does not modify the value of the current instance. Instead, it returns a new string in which all leading white space characters found in the current instance are removed.

Upvotes: 1

Charles Mager
Charles Mager

Reputation: 26213

string is immutable - what you're seeing is expected behaviour. Operations like TrimStart() will create a new string, which is returned when calling that method.

Why not do it in one go?

richTextBox1.Text = combindedString.TrimStart();

Upvotes: 2

Related Questions