Section106.1:System.Stringclass
InC#(and.NET)astringisrepresentedbyclassSystem.String.Thestringkeywordisanaliasforthisclass. The System.String class is immutable, i.e once created its state cannot be altered.
SoalltheoperationsyouperformonastringlikeSubstring,Remove,Replace,concatenationusing+operatoretc will create a new string and return it.
Seethefollowingprogramfordemonstration-
stringstr=”mystring”;
stringnewString=str.Substring(3);
Console.WriteLine(newString);
Console.WriteLine(str);
Thiswillprintstringandmystringrespectively.
Section106.2:Stringsandimmutability
Immutabletypesaretypesthatwhenchangedcreateanewversionoftheobjectinmemory,ratherthanchanging theexistingobjectinmemory.Thesimplestexampleofthisisthebuilt-instringtype.
Takingthefollowingcode,thatappends”world”ontotheword”Hello”
stringmyString=”hello”;
myString+=”world”;
Whatishappeninginmemoryinthiscaseisthatanewobjectiscreatedwhenyouappendtothestringinthe secondline.Ifyoudothisaspartofalargeloop,thereisthepotentialforthistocauseperformanceissuesinyour application.
ThemutableequivalentforastringisaStringBuilder
Takingthefollowingcode
StringBuildermyStringBuilder=newStringBuilder(“hello”);myStringBuild
er.append(“world”);
When you run this, youare modifying the StringBuilderobjectitself in memory.
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024