Voici un exemple d'utilisation d'un ArrayList. On crée un ArrayList dans lequel on ajoute des objets Person. Ensuite on les affiche dans un RichTextBox.

La classe Form1 avec la création des objets et leur affichage :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace LearnArrayList
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
			// Création du ArrayList
			ArrayList personList = new ArrayList();
			// Création d'un premier objet
			Person firstPerson = new Person("Toto", "Durand");
			// Ajout de l'objet au ArrayList
			personList.Add(firstPerson);
			// Création d'un second objet
			Person secondPerson = new Person("Jean-Claude", "Duss");
			// Ajout de l'objet au ArrayList
			personList.Add(secondPerson);
			// Affichage des objets
			PrintValues(personList);
		}
 
		private void PrintValues(IEnumerable personList)
		{
			// Création de l'énumérateur sur l'ArrayList
			IEnumerator personListEnumerator = personList.GetEnumerator();
			// Avancement de l'énumérateur dans la collection
			while (personListEnumerator.MoveNext())
			{
				// Cast de l'objet contenu dans la collection,
				// accès aux propriétés de l'objet,
				// et affichage dans une RichTextBox
				richTextBox1.AppendText(((Person)personListEnumerator.Current).firstName + " ");
				richTextBox1.AppendText(((Person)personListEnumerator.Current).lastName + "\n");
			}
		}
	}
}
La classe Person

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Collections.Generic;
using System.Text;
 
namespace LearnArrayList
{
	class Person
	{
		private string propFirstName = string.Empty;
		private string propLastName = string.Empty;
 
		public Person(string firstName, string lastName)
		{
			this.propFirstName = firstName;
			this.propLastName = lastName;
		}
 
		public string firstName
		{
			get { return (this.propFirstName); }
			set { this.propFirstName = value; }
		}
 
		public string lastName
		{
			get { return (this.propLastName); }
			set { this.propLastName = value; }
		}
	}
}