Saturday, May 21, 2011

C# and .NET interview questions - Describe about the various types of generic collections?

Answer:
There are basically four different types of generic collections which are as follows:-
1. List:-Lists are indexed based Generic Collections. Lists are Generic form of ArrayList.
List helps us to create flexible strong type collection as you can see in below code snippet i have defined List as "int" and "string".

//index based Generic collection          
List<int> ObjInt = new List<int>();       
ObjInt.Add(123);          
ObjInt.Add(456);          
Console.WriteLine(ObjInt[0]); //accessing the List by internal index based value.          
List<string> ObjString = new List<string>();          
ObjString.Add("feroz");

2. Dictionary:-Dictionary are key based generics collection.

Dictionary are generic form of Hashtable.

 //key based Generic collection          
Dictionary<int, int> ObjDict = new Dictionary<int,int>();          
ObjDict.Add(1,2);          
Dictionary<int, string> ObjDict1 = new Dictionary<int,string>();          
ObjDict1.Add(3, "feroz is a developer");          
ObjDict1.Add(4, "wasim is a developer");          
Console.WriteLine(ObjDict1[3]); //accessing the dictionary by defined key.

3. Stack:-Stack generic collection allows you to get value in "LIFO"(last in first out) manner.

// Stack           
Stack<string> ObjStack = new Stack<string>();          
ObjStack.Push("feroz");          
ObjStack.Push("moosa");          
Console.WriteLine(ObjStack.Pop());

4. Queue:-Queue generic collection allows you to get value in "FIFO"(first in first out) manner.

//Queue          
Queue<int> ObjStr = new Queue<int>();          
ObjStr.Enqueue(789);          
ObjStr.Enqueue(456);          
Console.WriteLine(ObjStr.Dequeue());



For more information about generic, please watch the below video.




Please click here to see more c# and Dotnet interview questions

Regards,

Visit Authors blog for more Most asked Dotnet interview questions


No comments: