- Home /
Arrays declaration c#
Hello everybody
Please i'm new here and i want to know how can i declare an Array i have tested this one but it doesn't work
Array aGrid =new Array();
Can anyone help me?
thx
Answer by leniency · Jan 26, 2012 at 05:00 AM
There are several ways to declare arrays:
int[] arr1 = new int[3]; // Create an integer array with 3 elements
var arr2 = new int[3]; // Same thing, just with implicit declaration
var arr3 = new int[] { 1, 2, 3 }; // Creates an array with 3 elements and sets values.
Lists, as Syclamoth mentioned are generic collections that will expand dynamically as you add elements. They do not require a size on declaration.
List<int> list1 = new List<int>();
var list2 = new List<int>();
var list3 = new List<int> { 1, 2, 3 }; // Initialize the list with 3 elements.
list3.Add(4); // Add a new element, list3.Count is now 4.
Answer by syclamoth · Jan 25, 2012 at 11:27 PM
In C# you don't use those Arrays. Even in JS you should avoid them- they're more trouble than they're worth.
Instead, use System.Collections.Generic.List-
using System.Collections.Generic;
List<TypeYouWantInTheList> aGrid = new List<TypeYouWantInTheList>();
The usage is almost exactly the same- List has many more functions, however. If you need to find out what it can do, look it up!
Arrays are still very useful when you have a fixed size and don't want the ($$anonymous$$mal) overhead of a List<>. Plus with Linq, you still get all the IEnumerable<> extensions regardless of using an array or list. $$anonymous$$ostly its about picking the right tool - whether you want to allow other components unrestricted growth, or a cap.
I'm more talking about the differences between the JS 'Array()' class and the similarly-used generic List. If you want builtin arrays, just use those, but they're not much different in C# than in JS. The question was specifically about alternatives to the Array class.
Answer by zakkar · Jan 26, 2012 at 10:02 AM
finally i have made this
Card[,] aGrid;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
aGrid[i,j]= new Card();
}
}
and i have declared a class of card which contain a string
thx
Your answer
Follow this Question
Related Questions
Declaring an Array as a combination of multiple other arrays? 1 Answer
Declare and clear an Array 3 Answers
Declaring a type in JavaScript arrays 3 Answers
Dynamic multi-dimensional array in C#? 2 Answers