Tuesday, November 29, 2016

Generics in C-sharp(C#)

Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

Some of the most useful features of Generics are:
  • type safety.
  • Eliminates type mismatch at run time.
  • Better performance with value type.
  • Does not incur inter conversion.
Generic | Creation of Generic List <T>

The procedure for using a generic List collection is similar to the concept of an array. We do declare the List, extend its sub members and then access the extended sub members of that List.

For example:

List<int> myInts = new List<int>(); 
myInts.Add(1);
myInts.Add(2);
myInts.Add(3);
for (int i = 0; i < myInts.Count; i++) 
   Console.WriteLine("MyInts: {0}", myInts[i]); 
}

Generic | Handling Dictionary <TKey , TValue> 

A Dictionary is nothing but a generic collection  that works with key/value pairs. A Dictionary works similarly to the way of non-generic collections such as a HashTable. The only difference between a Dictionary and a HashTable is that it operates on the object type.

The complete scenario of a Dictionary collection is explained through the example of customers.

For example:

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

Generic | Dictionary Collection

This code part represents dictionary handling with customer extended objects. It also explains how entries are extracted from a Dictionary.

For example:

Dictionary<int, Customer> customers = new Dictionary<int, Customer>(); 

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<int, Customer> custKeyVal in customers) 
   Console.WriteLine(
   "Customer ID: {0}, Name: {1}",
   custKeyVal.Key,
   custKeyVal.Value.Name); 
}


No comments:

Post a Comment

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...