Create and loop over a string array. Access array Length and get elements at indexes.
HomeSearchC#ArrayExamples,StringArraysCreateandloopoverastringarray.AccessarrayLengthandgetelementsatindexes.Array.ConsideraC#programthatstoresthenamesofanimals.Eachnameisastring—theanimalscanbestoredinanarray,andloopedoverandhandledtogether.Arrayusage.Arraysareinsidemanythings.Anarrayhaselements:theseallhavethesametype.In.NET,arraysarealow-levelwaytoholdobjectstogether.InitializeArrayStringarrays.Webeginwithstringarrays.Squarebracketsareusedforallarrays.Thesyntaxissimpleandeasytoremember(withpractice).Version1Thiscodecreatesastringarrayof3elements,andthenassignstringstothearrayindexes(startingat0).Version2Thisstringarrayiscreatedwithanarrayinitializerexpression.Itisshorterandeasiertotype.Version3Herewedonotevendeclarethetypeofthearray—thecompilercanfigureoutthebesttype.Version4Hereweusethenewkeywordalonetocreateastringarray.Thestringtypeisinferred.usingSystem;
classProgram
{
staticvoidMain()
{
//Version1:createemptystringarray.
//...Assignintothearray.
string[]animals=newstring[3];
animals[0]="deer";
animals[1]="moose";
animals[2]="boars";
Console.WriteLine("ARRAY1:"+animals.Length);
//Version2:usearrayinitializer.
string[]animals2=newstring[]{"deer","moose","boars"};
Console.WriteLine("ARRAY2:"+animals2.Length);
//Version3:ashorterarrayinitializer.
string[]animals3={"deer","moose","boars"};
Console.WriteLine("ARRAY3:"+animals3.Length);
//Version4:usenewwithnotypename.
string[]animals4=new[]{"deer","moose","boars"};
Console.WriteLine("ARRAY4:"+animals4.Length);
}
}ARRAY1:3
ARRAY2:3
ARRAY3:3
ARRAY4:3Firstandlast.Thefirstelementisatindex0.Andthelastelementisalwaysatthearray'slengthminusone.Theseelementscanbeaccessedbyusingtheindexersyntax.HereWecreatea4-elementintarrayandpopulateitwithafor-loop.Thenweaccesselement0andthelastelement.usingSystem;
classProgram
{
staticvoidMain()
{
//Createanarray.
int[]array=newint[4];
//Populatethearray.
intvalue=10;
for(inti=0;i
///Stringarrayfieldinstance.
///
string[]_elements={"one","two","three"};
///
///Stringarraypropertygetter.
///
publicstring[]Elements
{
get{return_elements;}
}
///
///Stringarrayindexer.
///
publicstringthis[intindex]
{
get{return_elements[index];}
}
}one
two
three
oneConvertstringarrays.Itispossibletousebuilt-inmethodslikeJoinandSplittoconvertastringarrayintoastring,andbackagain.WecanalsouseloopsandStringBuilder.PartAThisexampleusestheJoinmethodtocombinethe3stringliteralswithinthe"elements"array.JoinPartBFinallyweinvokeSplittochangeourjoinedstringbackintoastringarray.The2stringarraysareseparateinmemory.SplitInfoForconvertingastringarrayintoastring,wecanusemethodsbasedonStringBuilderaswell.ConvertArray,StringusingSystem;
classProgram
{
staticvoidMain()
{
string[]elements={"cat","dog","fish"};
Console.WriteLine(elements[0]);
//PartA:joinstringsintoasinglestring.
stringjoined=string.Join("|",elements);
Console.WriteLine(joined);
//PartB:separatejoinedstringswithSplit.
string[]separated=joined.Split('|');
Console.WriteLine(separated[0]);
}
}cat
cat|dog|fish
catStringargs.WhenaC#programisstarted,anoptionalstringarrayisreceivedfromtheoperatingsystem.Thisarray,args,containsstringarguments.MainargsStartTrycreatingashortcutinWindowstoyourC#executable.Theargsarrayisemptywhennoargumentsarepassed.HereIaddedtheargumentstring"helloworld"tothecommandintheWindowsshortcut.Thetwostringsarereceivedintotheargsarray.usingSystem;
classProgram
{
staticvoidMain(string[]args)
{
//...Loopoverargumentspassedtothisprogram.
foreach(stringvalueinargs)
{
Console.WriteLine("Argument:{0}",value);
}
}
}Argument:hello
Argument:worldReturnref,arrayelement.Withtherefkeyword,wecanreturnareferencetoanarrayelement.Herewehaveanintarray.FirstElementreturnsareftotheelementatindex0.ThenWecanassigntheresultofFirstElementtomodifythearray.The"codes"arrayismodified.classProgram
{
staticrefintFirstElement(int[]array)
{
//Returnreftofirstelementinarray.
returnrefarray[0];
}
staticvoidMain()
{
int[]codes={10,20,30};
//Changefirstelementtoanewvalue.
FirstElement(codes)=60;
//Displaymodifiedarray.
for(inti=0;ivalues)
{
//ThismethodcanbeusedwitharraysorLists.
foreach(intvalueinvalues)
{
Console.WriteLine("IENUMERABLE:"+value);
}
}
staticvoidMain()
{
int[]ids={10400,20800,40100};
//PasstheintarraytotheDisplaymethod,whichacceptsitasanIEnumerable.
Display(ids);
}
}IENUMERABLE:10400
IENUMERABLE:20800
IENUMERABLE:40100Exceptions.Wemustonlyaccesselementsinanarraythatarepresentinthearray.Thevaluescanbeanything,buttheaccessesmustoccurwithinthelengthofthearray.IndexOutOfRangeExceptionTipTomakearrayusageeasier,youcanaddhelpermethodsthatpreventout-of-rangeaccesses,butthiswillreduceperformance.usingSystem;
classProgram
{
staticvoidMain()
{
int[]test={10,20,30};
Console.WriteLine(test[4]);
}
}UnhandledException:System.IndexOutOfRangeException:Indexwasoutsidetheboundsofthearray.
atProgram.Main()in...Program.cs:line7Benchmark,arraycaching.Creatinganarrayhassomecost—memoryneedstobeallocated,anditwillneedtobegarbage-collected.Wecanoptimizebycachingarraysoftherequiredsizes.Version1Thiscodereusesastaticarrayof0elementseachtime,solessburdenisplacedontheruntime.Version2Herewecreateanew0-elementarrayeachtime—thecostsaddupsothisversionisseveraltimesslower.ResultIn2021(on.NET5forLinux)thecachedarrayismanytimesfaster—ithelpstoavoidcreatingarrays.usingSystem;
usingSystem.Diagnostics;
classProgram
{
constint_max=1000000;
staticvoidMain()
{
//Version1:useanemptyarraycachetoavoidcreatingmorethan1array.
vars1=Stopwatch.StartNew();
for(inti=0;i<_max if return s1.stop vars2="Stopwatch.StartNew();" for s2.stop console.writeline staticint return_emptyarraycache returnnewint>