I had been trying really hard about initializing a 1 dimensional array without knowing its size, but dont get it; Please tell me how can I declare a array whose size will dynamically increase as per the requirement in C#.
I mean, want to do something like开发者_运维知识库 this
class A
{
int[] myarray;
int i=0;
while(i<5)
{
myarray[i]==n;
n=n%10;
i++;
}
}
Please Help !!!
In C you would have to work with Malloc and Realloc, in C# you should prefer a List.
Class A {
List<int> integerList = new List<int>();
void DoSometing() {
for(int i = 0; i < somewhat; i++) {
integerList.Add(i);
}
}
}
In C++:
#include <vector>
// ...
std::vector<int> myVector; // will resize as you 'push_back'
The solutions in the languages are:
C: malloc()
and realloc()
C++: std::vector
C#: List
In C you use a malloc of a pointer.
In C++ you could just use a std::vector< T >.
In C# use a List< T >.
ie in C use a pointer in C++ and C# use one of the handy container classes.
It's so easy...
int IAmTheSize = 183475; // just a random int. Replace it with your value.
int[] myArray = new int[IAmTheSize];
You can initialize the array(s) with any size.
But if you don't know the precise size it will have, you might want to have a look at the List<>
class.
List<int> myList;
int i=0;
while(i < 5)
{
myList.Add(n);
n = n % 10;
i++;
}
From the operations you do, I realize this is some sort of exercising.
BTW, assigning a value in the array is done with the =
operator, like myarray[i]=n;
, not myarray[i]==n;
(will return a bool/boolean/logical value actually).
You can read more about the List<>
class here: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx
User can also declare this type of array using ARRAYLIST
System.Collections namespace defines a class known as ArrayList that can store dynamic sized array of objects.
ArrayList cities = new ArrayList();
cities.Add("Pune");
cities.Add("Mumbai");
精彩评论