C# Arrays (With Easy Examples) - TutorialsTeacher
文章推薦指數: 80 %
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;i
延伸文章資訊
- 1隱含類型陣列- C# 程式設計手冊 - Microsoft Docs
... 10, 100, 1000 }; // int[] var b = new[] { "hello", null, "world" }; // string[] // single-dim...
- 2c# array declaration with var Code Example - Code Grepper
“c# array declaration with var” Code Answer. c# initialize array. csharp by Binary Killer on Apr ...
- 3C# Arrays - W3Schools
Arrays are used to store multiple values in a single variable, instead of declaring separate vari...
- 4Day17-C#陣列Array、不規則陣列。神啊 - iT 邦幫忙
C#陣列簡介 · 1.陣列Array是多個相同資料型別的變數,在記憶體中連續串在一起的物件,需用new進行建立物件及宣告 · 2.宣告時由於是要跟電腦要一串連續的記憶體空間,陣列大小 ...
- 5C# - Creating a 'var' array of a fixed size? - Stack Overflow
However, you cannot create a var array, as var is not a type, but a keyword used in place of a ty...