0

I am trying to store data in an array like the following in a foreach loop:

firstname,lastname,dateofbirth

Therefore, once the loop has completed I should get {John,Smith,05/05/1980},{Mary,Smith,05/04/1980} etc... This will enable me to access different information for each person stored in the system.

What would be the best way to do this? I have been reading into using hierarchical arrays like those shown here http://msdn.microsoft.com/en-us/library/ms486189(v=office.12).aspx but I am not sure if this is the best method.

I am quite new to c# programming so any advice would be much appreciated!

1
  • The best way to do this is to write a class, with actual named properties. Way better than an array here. Commented Jul 16, 2012 at 17:02

2 Answers 2

5

The best way is to create a class to store the information.

public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
    public DateTime DateOfBirth {get; set;}
}

Then create a list of Person objects.

List<Person> people = new List<Person>()
people.Add(new Person() { FirstName = "John", LastName = "Smith", DateOfBirth = new DateTime(1980, 5, 5) });
Sign up to request clarification or add additional context in comments.

3 Comments

@ Juliusz. A struct sits on the call stack. A class has a reference on the call stack. It performs better this way. Structs are better for collections of value types (e.g. System.Drawing.Point).
Thanks Kyle. However I am getting an error on the .Add (I have used this before when using lists). What do I have to do add an 'Add' definition to the class?
Make sure you have a using System.Collections.Generic; entry at the top of the file. If that doesn't fix it, can you paste the exact error message you are getting?
2

Maybe use a stucture like this:

Class to hold individual person info:

public class Person
{
 public string FirstName {get;set;}
 public string LastName {get;set;}
 public DateTime DateOfBirth {get;set;}
}

List of people:

List<Person> people = new List<Person>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.