immutability - C# Changing a string after it has been created -


okay know question painfully simple, , i'll admit pretty new c# well. title doesn't describe entire situation here hear me out.

i need alter url string being created in c# code behind, removing substring ".aspx" end of string. know url, coming class, "blah.aspx" , want rid of ".aspx" part of string. assume quite easy finding substring, , removing if exists (or similar strategy, appreciate if has elegant solution if they've thought done before). here problem:

"because strings immutable, not possible (without using unsafe code) modify value of string object after has been created." msdn official website. i'm wondering now, if strings immutable, can't (shouldn't) alter string after has been made. how can make sure i'm planning safe?

string immutability not problem normal usage -- means member functions "replace", instead of modifying existing string object, return new one. in practical terms means have remember copy change original, like:

string x = "blah.aspx"; x.replace(".aspx", "");       // still "blah.aspx" x = x.replace(".aspx", "");   // "blah" 

the weirdness around strings comes fact system.string inherits system.object, yet, because of immutability, behaves value type rather object. example, if pass string function, there's no way modify it, unless pass reference:

void test(string y) {     y = "bar"; } void test(ref string z) {     z = "baz"; } string x = "foo"; test(x);                 // x still "foo" test(ref x);             // x "baz" 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -