What is the difference between ArrayList and Generic List in C#?

 Posted by Nagasundar_Tn on 12/1/2012 | Category: C# Interview questions | Views: 4602 | Points: 40
Answer:

Generic collections are TypeSafe at compile time. So No type casting is required. But ArrayList contains any type of objects in it. Here is the code snippet.

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());
}
}

}


In the above code I am using "list" obejct of ArralyList type and adding all types of values such as string, int, object of Program class. When printing I am considering everything as object and converting it into string. This part of code alone will print

hello

ConsoleApplication7.Program
4


But when coming to the second part "lstString" which is object of List<string> object will not compile when control comes to the following lines

             lstString.Add(new Program());   //Compiler error

lstString.Add(4); // Compiler Error



The output will be
Error:
The best overloaded method match for 'System.Collections.Generic.List<string>.Add(string)' has some invalid arguments.


Asked In: Nest Technology | Alert Moderator 

Comments or Responses

Login to post response