Array and ArrayList in C#

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

Problem

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

Solution

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.

  1. int[] intArray = new int[3];  
  2. Student student= new Student();  
  3. student.Id=1;  
  4. student.Email="[email protected]";  
  5. intArray[0] = 3;  
  6. intArray[1] = "pramod";  
  7. intArray[2] = student;  
  8.   
  9. class Student  
  10. {  
  11.       public int Id { getset; }  
  12.       public string Email { getset; }  
  13. }  
system string class

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.
  1. object[] intArray = new object[3];  
  2. intArray[0] = 3;  
  3. intArray[1] = "pramod";  
  4. Student student= new Student();  
  5. student.Id=1;  
  6. student.Email="[email protected]";  
  7. intArray[2] = student;  
student class

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.
  1. foreach (object obj in intArray)  
  2. {  
  3.       Console.WriteLine(obj);  
  4. }  
  5. 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.
  1. public override string ToString()  
  2. {  
  3.       return this.Email;  
  4. }  
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
  1. ArrayList intArray = new ArrayList();  
  2. intArray.Add(1);  
  3. intArray.Add("pramod");  
  4. Student student = new Student();  
  5. student.Id = 1;  
  6. student.Email = "[email protected]";  
  7. intArray.Add(student);  
array list

I hope you enjoy this article.

Happy coding. 

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    Learn
    View all