Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply Trim() to string without assignment to variable

Tags:

c#

trim

Is it possible to apply a Trim() to a string without assignment to a new or existing variable?

var myString = "  my string  ";
myString.Trim();

// myString is now value "my string"

Instead of having to assign it to a new variable or itself?

var myString = "  my string  ";
myString = myString.Trim();

// myString is now value "my string"
like image 237
Luke Avatar asked Aug 31 '15 14:08

Luke


2 Answers

No, that's not possible (within the use of the language).

The String class in .NET is immutable, which means that a specific string never will change. This allows for the code to pass strings around between methods without having to copy the strings to keep the original from changing.


The string is stored somewhere in memory, so if you go digging after it you could change the contents of the object and thereby change the value of the string. This however violates the rules for how strings work in the language, and you may end up changing a string that is used somewhere that you didn't anticipate.

String literals are interned by the compiler, which means that even if you have " my string " written in several places in the code, it will only be one string object when compiled. If you would change that string, you would change it for all places where it is used.

Example:

string test = "My string";

unsafe {
  // Note: example of what NOT TO DO!
  fixed (char* p = test) {
    *p = 'X';
  }
}

string another = "My string";
Console.WriteLine(another);

Output:

Xy string
like image 119
Guffa Avatar answered Nov 11 '22 23:11

Guffa


To formalize the comments, strings are immutable and cannot be changed in-line as you are wanting to do.

According to MSDN:

The value of the String object is the content of the sequential collection, and that value is immutable (that is, it is read-only).

It goes on to discuss the immutability in more depth:

A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.

Therefore, you cannot write a method (even as an extension since this and ref cannot be used together) that would cause the underlying string to physically be trimmed and return in the same line. You must assign the new value.

like image 4
Jason W Avatar answered Nov 11 '22 22:11

Jason W