hi.....
Oues-: What is Generic collection in c sharp with example ?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Datta KharadPosted Nov 19, 2011, 12:05 AM
Generic Collection:-
A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems.
Creating Generic List
The pattern for using a generic List collection is similar to arrays. You declare the List, populate its members, then access the members. Here's a code example of how to use a List:
List
myInts.Add(1);
myInts.Add(2);
myInts.Add(3);
for (int i = 0; i < myInts.Count; i++)
{
Console.WriteLine("MyInts: {0}", myInts[i]);
}
The first thing you should notice is the generic collection List
· ArrayList Class
· HashTable Class
· Stack Class and Queue class etc.
The main properties of the collection classes are
· Collection classes are defined as part of the System.Collection or System.Collections.Generic namespace.
· Most collection classes derive from the interfaces ICollection, IComparer, IEnumerable, IList, IDictionary, and IDictionaryEnumerator and their generic equivalents.
· Using generic collection classes provides increased type-safety and in some cases can provide better performance, especially when storing value types.
Example of Generic Collection:-
using System;
using System.Collections.Generic;
public class Customer
{
public Customer(int id, string name)
{
ID = id;
Name = name;
}
private int m_id;
public int ID
{
get { return m_id; }
set { m_id = value; }
}
private string m_name;
public string Name
{
get { return m_name; }
set { m_name = value; }
}
}
class Program
{
static void Main(string[] args)
{
List
myInts.Add(1);
myInts.Add(2);
myInts.Add(3);
for (int i = 0; i < myInts.Count; i++)
{
Console.WriteLine("MyInts: {0}", myInts[i]);
}
Dictionary
Customer cust1 = new Customer(1, "Cust 1");
Customer cust2 = new Customer(2, "Cust 2");
Customer cust3 = new Customer(3, "Cust 3");
customers.Add(cust1.ID, cust1);
customers.Add(cust2.ID, cust2);
customers.Add(cust3.ID, cust3);
foreach (KeyValuePair
{
Console.WriteLine(
"Customer ID: {0}, Name: {1}",
custKeyVal.Key,
custKeyVal.Value.Name);
}
Console.ReadKey();
}
Whenever coding with the generic collections, add a using System.Collections.Generic declaration to your file.