Hi, something I imagine would be simple but...
How can you create a class array? e.g.
MyClass[] mc = new MyClass[2](); ?????????
This obviously doesn't work, but how is it done?
Thanks for any advice in advance.
Ant
Nicholas Paldino [.NET/C# MVP] - 19 Aug 2006 17:58 GMT
Ant,
You need to do this:
MyClass[] mc = new MyClass[2];
Note, if MyClass is a reference type, then the references in the array
are all null, and you will have to populate them manually.
Hope this helps.

Signature
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
> Hi, something I imagine would be simple but...
>
[quoted text clipped - 6 lines]
> Thanks for any advice in advance.
> Ant
Siva M - 19 Aug 2006 18:08 GMT
The right syntax is MyClass[] mc = new MyClass[2];
However, this doesn't create two MyClass instances in the array. Rather, it
allocates two slots in the array to hold two MyClass instances. To complete
this further:
mc[0] = new MyClass();
mc[1] = new MyClass();
HTH
Hi, something I imagine would be simple but...
How can you create a class array? e.g.
MyClass[] mc = new MyClass[2](); ?????????
This obviously doesn't work, but how is it done?
Thanks for any advice in advance.
Ant
Philip Daniels - 19 Aug 2006 19:11 GMT
>The right syntax is MyClass[] mc = new MyClass[2];
>
[quoted text clipped - 17 lines]
>Thanks for any advice in advance.
>Ant
It's possible to use the array initialization syntax to create the
array in one shot. Given a class Foo with a constructor which takes a
string, the following is valid:
Foo[] classArray = new Foo[]
{
new Foo("hello"),
new Foo("world")
};
--
Philip Daniels
Ant - 20 Aug 2006 02:01 GMT
Hi Phillip,
That seems to be the neatest approach.
Thanks very much.
Ant
.
> >The right syntax is MyClass[] mc = new MyClass[2];
> >
[quoted text clipped - 30 lines]
> --
> Philip Daniels
Ant - 20 Aug 2006 02:00 GMT
Hello, thank you Siva,
Actually on my first try, I did in fact use "MyClass[] mc = new MyClass[2];"
Then I tried in vain using it with the constructor brackets when that didn't
work.
What I failed to do was instansiate the two objects in the array:
mc[0] = new MyClass();
mc[1] = new MyClass();
This did the trick.
Thanks kindly
> The right syntax is MyClass[] mc = new MyClass[2];
>
[quoted text clipped - 17 lines]
> Thanks for any advice in advance.
> Ant
Sir. mSait Özen - 21 Aug 2006 08:56 GMT
for(int i=0;i<mc.Lenght;i++)
{
mc[i]=new MyClass();
}
> Hi, something I imagine would be simple but...
>
[quoted text clipped - 6 lines]
> Thanks for any advice in advance.
> Ant