Dynamic Initialize in c#
I've a class
class sampleClass
{
...........
...........
public sampleClass()
{.........}
}
and in another class i created an array like
sampleClass[] X=new sampleClass[]{new sampleClass(),new sampleClass()}
here i gave 2 instance o开发者_运维技巧f the constructor. i need this dynamically..
that is the size of the array should be dynamically changed
It sounds like you want something like:
int size = // whatever
SampleClass[] array = new SampleClass[size];
for (int i = 0; i < size; i++)
{
array[i] = new SampleClass();
}
EDIT: If you really want to avoid a for loop, you could do something like:
SampleClass[] array = Enumerable.Range(0, size)
.Select(x => new SampleClass())
.ToArray();
... but I don't think that's actually better than using a loop.
This is just a syntactic sugar, you can gain the same using your own code:
sampleClass[] X = new sampleClass[num];
for(int i = 0; i < num; i++)
{
X[i] = new sampleClass();
}
You can initialize the array using a loop:
sampleClass[] X = new sampleClass[123];
for (int i = 0; i < X.Length; ++i)
X[i] = new sampleClass();
If your class was a value type the array is initialized when it is allocated:
struct sampleStruct { ... }
sampleStruct[] X = new sampleStruct[123];
// No need to initialize every array cell.
However, using a struct instead of a class is not something you should do simply to avoid a loop. You can read more about value types on MSDN.
精彩评论