Sunday, May 18, 2014

An Example of Generics using C# in ASP.NET

Introduction


 Developers like you are familiar with object-oriented programming and know the benefits it offers. One of the big benefits of object-oriented programming is code re-use, in which you create a base class and inherits in derived class. The derived class can simply override virtual methods or add some new methods to customize the behavior of the base class to meet yours need. The Generics is another mechanism offered by the common language runtime (CLR) and programming language that provides one more form of code re-use, algorithm re-use.

The generic is a code template that used to create type safe code without referring to specific data types. Generics allows you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. I want to discuss two benefits of generics one is type safety and another is performance before explain an example.

Type Safety

The Generics is mostly used for collection but framework class library also has non generic collection class like ArrayList, Hashtable, SortedList, Stack, Queue. So first of all we see an example of non-generic collection class means ArrayList where we add integer values in the array list and perform addition operation on the list values.

You need to create a class ArrayListOperation and define Addition method as following code snippet.

using System.Collections;
namespace TypeSafety
{
    class ArrayListOperation
    {
        public static int Addition()
        {
            ArrayList list = new ArrayList();
            list.Add(5);
            list.Add(9);

            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}

When you will run this code then you get return value from method.

As you have seen that in previous example there is array list of integer values and get result as expected but now add one more value in ArrayList that data type is float and perform same Addition operation. Let’s see updated code in following snippet.

using System.Collections;
namespace TypeSafety
{
    class ArrayListOperation
    {
        public static int Addition()
        {
            ArrayList list = new ArrayList();
            list.Add(5);
            list.Add(9);
            list.Add(5.10);

            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}

In the above code, all three values easily added to array list because ArrayList class Add() method values as a object type but when retrieving this values using each statement the each value will be assign in int data type variable but this array list has combination of both integer and float type value and float value won’t cast in int implicitly that why code will give an exception that is “Specified cast is not valid.” That’s means ArrayList is not type safe. An ArrayList is not type safe. What this means is that ArrayList can be assigned a value of any type.

Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. The System.Collections.Generics namespace contains the generics collections. Now let’s see an example with generic collection List.

using System.Collections.Generic;
namespace TypeSafety
{
    class ListOperation
    {
        public static int Addition()
        {
            List<int> list = new List<int>();
            list.Add(5);
            list.Add(9);            

            int result = 0;
            foreach (int value in list)
            {
                result += value;
            }
            return result;
        }
    }
}

In above code we define a list int type means we can only add integer value in the list and can’t add float value to it so when we retrieve values from the list using foreach statement then we get only int value. You will run this code then you get return value from method. Now you can say generic collection is type safe.

Performance

Before discussion of performance we need to know about object data type in C# so what is object data type? From msdn “The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed.” Hope it make sense.

Before generics, the way to define a generalized algorithm was to define its entire member to the Object data type. If you wanted to use the algorithm with value type instances, the CLR had to box the value type instance prior to calling the members of the algorithm. This boxing causes memory allocations on the managed heap, which causes more frequent garbage collections, which, in turn, hurt an application's performance.

Since a generic algorithm can now be created to work with a specific value type, the instances of the value type can be passed by value, and the CLR no longer has to do any boxing. In addition, since casts are not necessary, the CLR doesn't have to check the type safety of the attempted cast, and this results in faster code too.

Now let’s see syntax of Add() method for non generic and generic collection class. We are discussion two collection classes one for non generic (ArrayList) and another is generic (List).

Syntax of Add() method of ArrayList: public virtual int Add(object value);

The above line of method signature represents that each value that would be add in ArrayList, will be object type means if you are using value type to add in ArrayList then it will be cast in object type before add to ArrayList.

Syntax of Add() method of Listpublic void Add(T item);

The above line of method signature represents that there is no need to cast to add an item to generic type list. If List type is T then item will be T type.

Now you know who has better performance. Generic collection class has better performance over non generic collection class. Let’s see an example in below code snippet.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Performance
{
    class Program
    {
        static void Main(string[] args)
        {
            NonGenericPerformance();
            GenericPerformance();
            Console.ReadKey();
        }
        static void NonGenericPerformance()
        {
            long operationTime = 0;
            ArrayList arraylist = new ArrayList();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 1; i <= 100000; i++)
            {
                arraylist.Add(i);
            }
            operationTime = sw.ElapsedMilliseconds;
            Console.WriteLine("Array List {0} values add time is {1} milliseconds", arraylist.Count, operationTime);
            sw.Restart();
            foreach (int i in arraylist)
            {
                int value = i;
            }
            operationTime = sw.ElapsedMilliseconds;
            Console.WriteLine("Array List {0} values retrieve time is {1} milliseconds", arraylist.Count, operationTime);
        }
        static void GenericPerformance()
        {
            long operationTime = 0;
            List<int> list = new List<int>();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 1; i <= 100000; i++)
            {
                list.Add(i);
            }
            operationTime = sw.ElapsedMilliseconds;
            Console.WriteLine("List {0} values add time is {1} milliseconds", list.Count, operationTime);
            sw.Restart();
            foreach (int i in list)
            {
                int value = i;
            }
            operationTime = sw.ElapsedMilliseconds;
            Console.WriteLine("List {0} values retrieve time is {1} milliseconds", list.Count, operationTime);
        }
    }

}

Let’s run the above code and get result as figure 1.1
 
An Example of Generics using C# in ASP.NET






Figure 1.1 Performance between generic and non generic collection.

How to reuse code using generic?

Here I am going to introduce a simple concept of code reuse using generic. I will populate UI lists (Dropdown, Checkbox, RadioButton) using a common method. So let’s see code.

First of all creates a table Master that has three fields as Id, Title and Type (UI entity type). Let’s see database script for table creation and database insertion.

Create Table Master
(
Id int identity(1,1) primary key,
Title nvarchar(50) not null,
Type int not null
)

Insert Into Master values ('Jaipur',1),('Jhunjhunu',1),
('Cricket',2),('Football',2),('Male',3),('Female',3)

Now creates an enum for types on UI as per our form design requirement.

namespace GenericUIList
{
    public enum Types
    {
        NativePlace = 1,
        Hobby = 2,
        Gender = 3
    }
}

Here enum attributes values same as Type field values in database table Master.

Write connection string on code behind like

<connectionStrings>   
    <add name ="genericConn" connectionString="Data Source=SANDEEPSS-PC;database=Development;user=sa;password=******"/>
</connectionStrings>

Now design a form that has three lists for NativePlace (Dropdownlist), Hobbies (Checkbox list) and Gender (Radio button list) as per following code snippet.

<p>Native Place : <asp:DropDownList ID="ddlNativePlace" runat="server"></asp:DropDownList></p>
<p>Hobbies : <asp:CheckBoxList ID="chkHobbies" runat="server"></asp:CheckBoxList></p>
<p>Gender : <asp:RadioButtonList ID="rbGender" runat="server"></asp:RadioButtonList></p>

Now we create a generic method on code behind file and call that method on page load. Lets see following code snippet on .cs page of web form.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace GenericUIList
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PopulateUIList<DropDownList>(ddlNativePlace, Types.NativePlace);
                PopulateUIList<CheckBoxList>(chkHobbies, Types.Hobby);
                PopulateUIList<RadioButtonList>(rbGender, Types.Gender);
            }
        }
        public void PopulateUIList(T list, Types type) where T : ListControl
         {
             string connectionString = ConfigurationManager.ConnectionStrings["genericConn"].ConnectionString;
             using (SqlConnection con = new SqlConnection(connectionString))
             {
                 if(con.State == ConnectionState.Closed)
                 {
                     con.Open();
                 }
                 string cmdText = "Select Id,Title from Master Where Type = @type";
                 using (SqlCommand cmd = new SqlCommand(cmdText, con))
                 {
                     cmd.Parameters.Add(new SqlParameter("@type",(int)type));
                     DataTable dt = new DataTable();
                     IDataReader dr = cmd.ExecuteReader();
                     dt.Load(dr);
                     list.DataSource = dt;
                     list.DataTextField = "Title";
                     list.DataValueField = "Id";
                     list.SelectedIndex = 0;
                     list.DataBind();
                 }
             }
         }
    }
}

Run the application and get result on page as figure 1.2.



If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website