Array and ArrayList in C#

Introduction

In this article we learn what an array object and ArrayList are in C#.

Problem Statement

I have a scenario where I need to store various data types in an array. Is it possible in C#?

Solution to the problem

Yes it is possible. We can do this using either of two ways. By using an array object or an ArrayList.

First create a console application and name it OopsTutorial.

Method 1

Let's make an array that is an integer type and put some data into it.

int[] intArray = new int[3];  
Student student= new Student();  
student.Id=1;  
student.Email="[email protected]";  
intArray[0] = 3;  
intArray[1] = "pramod";  
intArray[2] = student;  
  
class Student  
{  
      public int Id { get; set; }  
      public string Email { get; set; }  
}  

When we assign a value in the array there is a compile time error that says we cannot implicitly convert type string to int. Array is strongly typed. It means if I have created an array that is an integer type then the array will accept only an integer typed value. But if I want to store various data types in an array I need to create an array that has a type object.

object[] intArray = new object[3];  
intArray[0] = 3;  
intArray[1] = "pramod";  
Student student= new Student();  
student.Id=1;  
student.Email="[email protected]";  
intArray[2] = student;

 After creating an object array there is no error, because the object type is the base type of all types in .Net.

Before executing the application let's write some code to print the details and hit F5.

foreach (object obj in intArray)  
{  
      Console.WriteLine(obj);  
}  
Console.ReadLine();  

Output

output

The first and second line of the output is fine for me but what is the third line? It shows NamespaceName.MyClassName, that I don't want to see. I just want to see the student email id. So let's make some other changes to the student class. I will override the ToString() method in the student class and press F5.

public override string ToString()  
{  
      return this.Email;  
}  

Method 2

The ArrayList class is present in the System.Collections namespace. By using ArrayList we can do this. Just replace this code over an object array and run it, the output will be the same.

arraylist class

ArrayList intArray = new ArrayList();  
intArray.Add(1);  
intArray.Add("pramod");  
Student student = new Student();  
student.Id = 1;  
student.Email = "[email protected]";  
intArray.Add(student);  q

array list

I hope you enjoy this article.


Similar Articles