Monday, 11 May 2015

Difference between Generics and Collections with example

Generics provides the type safe code with re-usability like as algorithm. In algorithms such as sorting, searching, comparing etc. you don’t specify what data type(s) the algorithm operates on. The algorithm can be operates with any types of data. In the same way Generics operate, you can provide different data type to Generics. For example, a sorting algorithm can operates on integer type, decimal type, string type, DateTime type etc.

The .Net framework provides the Generic type for collection classes and these classes ensure that a specific type of data can be stored in the collection. Now, we will discuss the generic type of ArrayList, i.e. List <T> class. Generics are the most powerful feature of C# 2.0. Generics allow us to define type-safe data structures. Generic collection types also generally perform better than the corresponding nongeneric collection types.

A generic collection is strongly typed (type safe), meaning that we can store only one type of data into the collection. This ensures there are no type mismatches at runtime. An additional benefit of generic collection is that performance is better because we do not need to converted them to actual object.

Suppose we want to store only integer values in a collection, we will specify the integer type for the generic parameter. The below code shows how to create a List. Note the data type between less than and greater than symbol <int>. This is how data type is declared at the time of instantiating the List object. In place of int we can use any type of object, like string or a custom business object.

Here I listed some comparesions between Collections and Generics:-






















// A class employee
 class Employee
    {
        public int EmpNumber { getset; }
        public string EmpName { getset; }
    }


With Collection:-


    ArrayList Obj = new ArrayList();

      // Add to ArrayList
            emp.EmpNumber=101;
            emp.EmpName="Rampal";
            Obj.Add(emp);

     // Display ArrayList Item
           foreach (Object s in Obj)
            {
                //Type-casting. If s is anything other than a student 
                Employee emp = (Employee)s;
                Console.Write(emp.EmpNumber +"   "+ emp.EmpName);
                Console.Write("\n");
            }

     //Fooling Compiler
              Obj.Add("AnyObject");  // It will acept no type safety


With Generics:-


    List ListObj= new yList();

      // Add to List
            emp.EmpNumber=101;
            emp.EmpName="Rampal";
            ListObj.Add(emp);

     // Display List Item
           foreach (Object s in ListObj)
            {
                // No Type-casting.  
                Employee emp = (Employee)s;
                Console.Write(emp.EmpNumber +"   "+ emp.EmpName);
                Console.Write("\n");
            }


     // Cat't make Compiler fool
              ListObj.Add("AnyObject");  // It will not acept no type safety

 Error:-





Now using Code:-

Collections:-


using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Test_ArrayList classObj = new Test_ArrayList();
            while (true)
            {
                // Console.Clear();
                Console.WriteLine("\n");
                Console.WriteLine("1. Add an Item to ArrayList");
                Console.WriteLine("2. Display ArrayList Items");
                Console.WriteLine("3. Exit");
                Console.Write("Select your choice: ");
                int choice = Convert.ToInt32(Console.ReadLine());
                switch (choice)
                {
                    case 1:
                        classObj.Add();
                        break;

                    case 2: classObj.Display();
                        break;
                  
                    case 3: System.Environment.Exit(1);
                        break;
                }
                Console.ReadKey();
            }
        }
    }

    class Employee
    {
        public int EmpNumber { get; set; }
        public string EmpName { get; set; }
    }
    public class Test_ArrayList
    {
        int Num;
        string Name;
        ArrayList Obj = new ArrayList();
        Employee emp = new Employee();

        // Add an Item to ArrayList
        public void Add()
        {
            Console.WriteLine("\nEnter employee number: ");
            Num = int.Parse(Console.ReadLine());
            Console.WriteLine("\nEnter employee Name: ");
            Name = Console.ReadLine();
            emp.EmpNumber=Num;
            emp.EmpName=Name;
            Obj.Add(emp);
             Console.Write("\nAdded successfully! \n");
        }

        // Display Items in the ArrayList
        public void Display()
        {
          
            Console.Write("\nItem in ArrayList");
            Console.Write("\n");
            Console.Write("\nEmpNo"+"   "+ "EmpName\n");
            foreach (Object s in Obj)
            {
                //Type-casting. If s is anything other than a student 
                Employee emp = (Employee)s;
                Console.Write(emp.EmpNumber +"   "+ emp.EmpName);
                Console.Write("\n");
            }
        }
      
    }

}



Output:-






















































Generics:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Test_List classObj = new Test_List();
            while (true)
            {
                // Console.Clear();
                Console.WriteLine("\n");
                Console.WriteLine("1. Add an Item to List");
                Console.WriteLine("2. Display List Items");
                Console.WriteLine("3. Exit");
                Console.Write("Select your choice: ");
                int choice = Convert.ToInt32(Console.ReadLine());
                switch (choice)
                {
                    case 1:
                        classObj.Add();
                        break;

                    case 2: classObj.Display();
                        break;
                  
                    case 3: System.Environment.Exit(1);
                        break;
                }
                Console.ReadKey();
            }
        }
    }

    class Employee
    {
        public int EmpNumber { get; set; }
        public string EmpName { get; set; }
    }
    public class Test_List
    {
        int Num;
        string Name;
        List<Employee> ListObj = new List<Employee>();
        Employee emp = new Employee();

        // Add an Item to List
        public void Add()
        {
            Console.WriteLine("\nEnter employee number: ");
            Num = int.Parse(Console.ReadLine());
            Console.WriteLine("\nEnter employee Name: ");
            Name = Console.ReadLine();
            emp.EmpNumber=Num;
            emp.EmpName=Name;
            ListObj.Add(emp);
             Console.Write("\nAdded successfully! \n");
        }

        // Display Items in the List
        public void Display()
        {
          
            Console.Write("\nItem in List");
            Console.Write("\n");
            Console.Write("\nEmpNo"+"   "+ "EmpName\n");
            foreach (Object s in ListObj)
            {
                //no need to type cast since compiler already knows that everything inside
                //this list is a Employee
                Employee emp = (Employee)s;
                Console.Write(emp.EmpNumber +"   "+ emp.EmpName);
                Console.Write("\n");
            }
        }
      
    }
}



Sunday, 10 May 2015

What is boxing and unboxing in c# .net ?

C# Type System contains three Types , they are Value Types , Reference Types and Pointer Types. C# allows us to convert a Value Type to a Reference Type, and back again to Value Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.














Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.

Boxing using code:-


  •   int Val = 1;
  •   Object Obj = Val;   //Boxing


The first line we created a Value Type Val and assigned a value to Val. The second line , we created an instance of Object Obj and assign the value of Val to Obj. From the above operation (Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.

UnBoxing using code:-
  • int Val = 1;
  • Object Obj = Val;        //Boxing
  • int i = (int)Obj;            //Unboxing


The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.

Boxing and UnBoxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed , also the cast required for UnBoxing is also expensive computationally.


Source code example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleDemoApp
{
    class Test
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\n");
            Console.WriteLine("Enter a Integer value");
            int value = Convert.ToInt32(Console.ReadLine());

            //Boxing implicit conversion
            Object Obj = value;
            Console.WriteLine("Boxing(Object/Boxed Value) : {0}\n", Obj.ToString());

            //Unboxing explicit conversion
            int num = (int)Obj;
            Console.WriteLine("UnBoxing(Entered Number Value): {0}\n", num);
            Console.ReadKey();
        }
    }
}

  

Output:-