Search code examples
c#trim

Apply Trim() to string without assignment to variable


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"

Solution

  • 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