Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `String.Trim()` not trim the object itself?

Tags:

c#

Not often but sometimes I need to use String.Trim() to remove whitespaces of a string.
If it was a longer time since last trim coding I write:

string s = " text ";
s.Trim();

and be surprised why s is not changed. I need to write:

string s = " text ";
s = s.Trim();

Why are some string methods designed in this (not very intuitive) way? Is there something special with strings?

like image 474
brgerner Avatar asked Nov 27 '22 04:11

brgerner


1 Answers

Strings are immutable. Any string operation generates a new string without changing the original string.

From MSDN:

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.

like image 110
Tudor Avatar answered Dec 15 '22 07:12

Tudor