C# Arrays (With Easy Examples) - TutorialsTeacher

文章推薦指數: 80 %
投票人數:10人

A variable is used to store a literal value, whereas an array is used to store multiple literal values. An array is the data structure that ... C# ASP.NETCore MVC IoC TypeScript Angular Python SQLServer MongoDB More ✕ .NETTutorials C# ASP.NETCore ASP.NETMVC IoC webapi LINQ ClientSide JavaScript jQuery Node.js D3.js TypeScript Angular11 AngularJS1 Sass ServerSide https Python SQL SQLServer PostgreSQL MongoDB SkillTests ASP.NETCore ASP.NETMVC LINQ C# webapi IoC TypeScript AngularJS Node.js jQuery JavaScript Articles Tests LearnC# C#-GetStarted C#-VersionHistory C#-FirstProgram C#-Keywords C#-Class C#-Variable C#-Implicitly-TypedVariable C#-DataTypes Numbers Strings DateTime Structure Enum StringBuilder AnonymousTypes DynamicTypes NullableTypes C#-Value&ReferenceTypes C#-Interface C#-Operators C#-ifelseStatements C#-TernaryOperator?: C#-Switch C#-ForLoop C#-WhileLoop C#-Do-whileLoop C#-PartialClass C#-Static C#-Array MultidimensionalArray JaggedArray C#-Indexer C#-Generics GenericConstraints C#-Collections ArrayList List SortedList Dictionary Hashtable Stack Queue C#-Tuple C#-ValueTuple C#-Built-inExceptions ExceptionHandling throw CustomException C#-Delegates FuncDelegate ActionDelegate PredicateDelegate AnonymousMethods C#-Events C#-Covariance C#-ExtensionMethod C#-StreamI/O C#-File C#-FileInfo C#-ObjectInitializer C#-UsefulResources Previous Next C#Arrays Updatedon:May10,2020 Avariableisusedtostorealiteralvalue,whereasanarrayisusedtostoremultipleliteralvalues. Anarrayisthedatastructurethatstoresafixednumberofliteralvalues(elements)ofthesamedatatype.Arrayelementsarestoredcontiguouslyinthememory. InC#,anarraycanbeofthreetypes:single-dimensional,multidimensional,andjaggedarray.Hereyouwilllearnaboutthesingle-dimensionalarray. Thefollowingfigureillustratesanarrayrepresentation. ArrayRepresentation ArrayDeclarationandInitialization Anarraycanbedeclaredusingbyspecifyingthetypeofitselementswithsquarebrackets. Example:ArrayDeclaration int[]evenNums;//integerarray string[]cities;//stringarray Thefollowingdeclaresandaddsvaluesintoanarrayinasinglestatement. Example:ArrayDeclaration&Initialization int[]evenNums=newint[5]{2,4,6,8,10}; string[]cities=newstring[3]{"Mumbai","London","NewYork"}; Above,evenNumsarraycanstoreuptofiveintegers.Thenumber5inthesquarebracketsnewint[5]specifiesthesizeofanarray. Inthesameway,thesizeofcitiesarrayisthree.Arrayelementsareaddedinacomma-separatedlistinsidecurlybraces{}. Arraystypevariablescanbedeclaredusingvarwithoutsquarebrackets. Example:ArrayDeclarationusingvar varevenNums=newint[]{2,4,6,8,10}; varcities=newstring[]{"Mumbai","London","NewYork"}; Ifyouareaddingarrayelementsatthetimeofdeclaration,thensizeisoptional.Thecompilerwillinferitssizebasedonthenumberofelementsinsidecurlybraces,asshownbelow. Example:ShortSyntaxofArrayDeclaration int[]evenNums={2,4,6,8,10}; string[]cities={"Mumbai","London","NewYork"} Thefollowingexampledemonstrateinvalidarraydeclarations. Example:InvalidArrayCreation //mustspecifythesize int[]evenNums=newint[]; //numberofelementsmustbeequaltothespecifiedsize int[]evenNums=newint[5]{2,4}; //cannotusevarwitharrayinitializer varevenNums={2,4,6,8,10}; LateInitialization Itisnotnecessarytodeclareandinitializeanarrayinasinglestatement.Youcanfirstdeclareanarraytheninitializeitlateronusingthenewoperator. Example:LateInitialization int[]evenNums; evenNums=newint[5]; //or evenNums=newint[]{2,4,6,8,10}; AccessingArrayElements Arrayelementscanbeaccessedusinganindex.Anindexisanumberassociatedwitheacharrayelement,startingwithindex0andendingwitharraysize-1. Thefollowingexampleadd/updateandretrievearrayelementsusingindexes. Example:AccessArrayElementsusingIndexes int[]evenNums=newint[5]; evenNums[0]=2; evenNums[1]=4; //evenNums[6]=12;//Throwsrun-timeexceptionIndexOutOfRange Console.WriteLine(evenNums[0]);//prints2 Console.WriteLine(evenNums[1]);//prints4 Tryit NotethattryingtoaddmoreelementsthanitsspecifiedsizewillresultinIndexOutOfRangeException. AccessingArrayusingforLoop Usetheforlooptoaccessarrayelements.Usethelengthpropertyofanarrayinconditionalexpressionoftheforloop. Example:AccessingArrayElementsusingforLoop int[]evenNums={2,4,6,8,10}; for(inti=0;iConsole.WriteLine(n));//iteratesarray Array.BinarySearch(nums,5);//binarysearch Tryit PassingArrayasArgument Anarraycanbepassedasanargumenttoamethodparameter.Arraysarereferencetypes,sothemethodcanchangethevalueofthearrayelements. Example:PassingArrayasArgument publicstaticvoidMain(){ int[]nums={1,2,3,4,5}; UpdateArray(nums); foreach(variteminnums) Console.WriteLine(item); } publicstaticvoidUpdateArray(int[]arr) { for(inti=0;i



請為這篇文章評分?