What is the difference between ArrayList and Generic List in C#?
Arraylist:
- It is like Array of objects.
- "System.Collections" is the Namespace for Arraylist. It automatically added to namespace section in aspx.cs page.
- We need not to specify object type arraylist going to contain.
- In arraylist each item is stored as object. And return value as object.
- It needs to box and unbox the elements.
- No type safety (Compile time)
List<T>:
- "System.Collections.Generic" is the Namespace for List. We need to add this.
- We need to specify object type which type of elements it contain.
- Ex: List<string> StrObj=new List<string>();
- From the above example StrObj will only store string objects.
- It doesn't need.
- Type safety (compile time)
namespace Example
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add("hello");
list.Add(new Program()); // Oops! That's not meant to be there...
list.Add(4);
foreach (object o in list)
{
Console.WriteLine(o.ToString());
}
List<string > lstString = new List<string>();
lstString.Add("ABCD");
lstString.Add(new Program()); //Compiler error
lstString.Add(4); // Compiler Error
foreach (object o in lstString)
{
Console.WriteLine(o.ToString());
} }
}
No comments:
Post a Comment