Array of Class Question

J

jm

I'm looking at this code at MSDN:

http://msdn2.microsoft.com/en-us/library/system.collections.ienumerable.aspx

using System;
using System.Collections;

public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}

public string firstName;
public string lastName;
}

public class People : IEnumerable
{
private Person[] _people; //trying to understand this line
....

I wanted to know how they "all of a sudden" were able to declare the
variable _people as an array of Person[] user defined types. I didn't
see anything that would allow Person to be used as an array like this.
Probably something basic I forgot somewhere, but I can't find the
answer.

Thank you.
 
L

Lebesgue

You can declare an array of any type in C#:
int[] or Person[] , they are both instances of System.Array.
I think you are searching for problems in the place they are not present in
:)
 
M

Marc Gravell

Arrays are supported out-of-the-box for any type. There is no
distinction between user-defined an MS-defined. In fact SomeType[]
could really be considered as a 1.1 precursor to generics.

Note that the line in question doesn't *allocate* an array - just says
that _people *is* an array; if you added

_peope = new Person[10];

then it would allocate enough space for 10 Person references (it Person
was a struct it would allocate the space for the actual instances).
This *still* doesn't get you any people (they are all null references),
so you then need:

for(int i = 0; i < 10; i++) {
_people = new Person();
}

et voila; 10 people; you can then access _people[0] thru _people[9]

Arrays in this usage are a fundamental concept provided by the runtime
/ compiler in most languages without having to involve the targetted
class. Suggest you read up on Array on MSDN...

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top