Is there a way to declare and use an array of classes using a constructor
that takes parameters i.e.
class something
{
int var1;
double var2;
something(int var, double variable)
{
var1 = var; var2 = variable
}
something()
{
var1 = 0; var2 = 0.00;
}
}
class MainClass
{
something[] manytypes = new something(2, 4.305)[2];
}
I want 2 types of the something class but the compiler gives an error. How
can I do this?
Jon Skeet [C# MVP] - 25 Mar 2008 20:04 GMT
> Is there a way to declare and use an array of classes using a constructor
> that takes parameters i.e.
[quoted text clipped - 22 lines]
> I want 2 types of the something class but the compiler gives an error. How
> can I do this?
Create the array, and then populate it:
something[] manytypes = new something[2];
for (int i=0; i < manytypes.Length; i++)
{
manytypes[i] = new something(2, 4.305);
}

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Peter Duniho - 25 Mar 2008 20:12 GMT
> [...]
> class MainClass
[quoted text clipped - 5 lines]
> How
> can I do this?
With a relatively small number of array elements, it's simple enough to
write:
something[] manytypes = { new something(2, 4.305), new something(2,
4.305) };
Of course, while more lengthy for small numbers of elements, it'd be more
maintainable to write:
something[] manytypes = new something[2];
for (int i = 0; i < manytypes.Length; i++)
{
manytypes[i] = new something(2, 4.305);
}
And for longer arrays, that's actually likely to be easier.
And of course, if the "something" class is immutable, you could even write:
something init = new something(2, 4.305);
something[] manytypes = new something[2];
for (int i = 0; i < manytypes.Length; i++)
{
manytypes[i] = init;
}
That would be more efficient than creating a new instance of the class for
each array element.
Pete
amir - 25 Mar 2008 20:20 GMT
Thank you both for the insight. It helps a great deal to know there is some
one smarter.
Cheers..