Saturday, April 18, 2020

Difference between array and arraylist in c#

Introduction

This blog will give us an idea of the  differences between Array and ArrayList and we can figure out when to use Array and when to use ArrayList while programming. Basically, this an interview question. So this is helpful for beating an interview also.

Array

Arrays are strongly-typed collections of the same data type and have a fixed length that cannot be changed during runtime. We can access the Array elements by numeric index. The array indexes start at zero. The default value of numeric array elements is set to zero, and the reference elements are set to null.
Difference Between Array And ArrayList In C#
Example
Difference Between Array And ArrayList In C#

ArrayList

An Array list is not a strongly-typed collection. It can store the values of different data types or same datatype. The size of an array list increases or decreases dynamically so it can take any size of values from any data type. ArrayList is one of the most flexible data structures from C# Collections. ArrayList contains a simple list of values. ArrayList implements the IList interface using an array and very easily we can add, insert, delete, view etc. It is very flexible because we can add without any size information that is it will grow dynamically and also shrink.
Example
Difference Between Array And ArrayList In C#

Differences between Array and ArrayList

 
SrArrayArrayList
1Array is strongly typed. This means that an array can store only specific type of items\elementsArrayList can store any type of items\elements.
2In arrays we can store only one datatype either int, string, char etc…In arraylist we can store all the datatype values
3Array cant accept nullArrayList collection accepts null
4Arrays belong to System.Array namespace
using System;
Arraylist belongs to System.Collection namespaces
using System.Collections;
5Example -
int[] intArray=new int[]{2};
intArray[0] = 1;
intArray[2] = 2;
Example -
ArrayList Arrlst = new ArrayList();
Arrlst.Add("Sagar");
Arrlst.Add(1);
Arrlst.Add(null);
 

No comments:

Post a Comment