Click here to Skip to main content
15,867,594 members
Articles / Extension
Article

Using Extension methods in ASP.NET 3.0 and 3.5 with generics.

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL5 min read 6.4K   1  
Since the dawn of asp.net, web based development has become a lot easier.  It provides a great deal of control over designs and code.  And affords

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Since the dawn of asp.net, web based development has become a lot easier.  It provides a great deal of control over designs and code.  And affords the developer more power over his/her business logic; rather than becoming bogged down with the roughness of using old scripting languages. 

MS continues to change it - improving the process of Web based development.  The best things I like about MS technologies:  they're highly reusable and very flexible.  So now, without wasting anymore time, I will jump to the main topic:  using extension methods in asp.net.

I assume that most of the readers have heard about the extension methods at least once; however, here's a brief description about extension methods:

"Extension methods are very cleverly designed tool to create more sense-full and reusable code for any particular scenario which is repeatable in various situations and scenarios.  These are static classes which contains one or many static methods which can be directly injected in to the required object for a defined purpose"

I will not explain why and how it is reusable, Although i will demonstrate a example which will explain my definition of Extension methods.

Just take an example that you have a multi select list box, where you select multiple items from it. this is the best you can do with any listbox. but each time you will do this, to find selected items you have to loop through all the items of listbox. It may be condition that you need selected item array in some defined data types. such as string, int, float, double, datetime etc.
Now you can say i can use generics for that why should I use extension methods. So the answer is as follows. in todays IT development time line is always limited and the workload keeps on increasing, as Project managers always says, "This can be done in 5 mins!", but they never tell HOW?. Now in such a situation a developer works like a BULL, day in day out, and most of the time we all redundant our code and put some patch work just to finish the target. But we never think that the more and more code we write the more time it take to manage it.

OK enough talking. Now getting out of my project manager's dilemma here is an simple example of Extension method using generics.

So here I am trying to create a method which will give me all the selected items of any listbox in an array in the data type format I want.

So first create one listbox with some string values, or copy from below

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" >
        <asp:ListItem>India</asp:ListItem>
        <asp:ListItem>Australia</asp:ListItem>
        <asp:ListItem>Spain</asp:ListItem>
        <asp:ListItem>Denmark</asp:ListItem>
        <asp:ListItem>Egypt</asp:ListItem>
        <asp:ListItem>Qatar</asp:ListItem>
        <asp:ListItem>Nepal</asp:ListItem>
        <asp:ListItem>China</asp:ListItem>
        <asp:ListItem>Brazil</asp:ListItem>
    </asp:ListBox>

As you can see i have a List box whose ID is ListBox1 where selection mode is multiple.
so on the run time i can select more then one country or all, and my requirement is to get all the selected items should come in string array.

now create one class or in the  code behind of this aspx copy and paste code given below under the same namespace.
////////////////////////////
public static class ControlExtentions
    {
        // Using ListBox Class to inject this method in ListBox Class
        // Using <T> for getting resultant array in desired format
 public static T[] ToListArray<T>(this ListBox control) where T : IConvertible
        {
            // Create List Array Object Of type <T> in local variable newList type var
            var newList = new List<T>();
     // Now loop through all the items of this Listbox
            foreach (ListItem li in control.Items)
            {
               // check every item if it is selected

               if (li.Selected)
                {
  `   // If selected then change the type of currently selected item's Text in to type T and
         add it into newList.
                    newList.Add((T)Convert.ChangeType(li.Text, typeof(T)));
               
                }

            }
     // finally return then List into Array Format
            return newList.ToArray();
        }

    }
}
//////////////////////////

It is fairly easy and simple to understand how above method will work, well you can also go through the code comment.
Now how to use this.
As i have use this class under same name space to demonstrate the logic we don't have to add any namespace fore this, but it is strongly advised that you use method in separate class so the scope of this method will be increased. and then you just have to use this name space in your code behind.

OK Ya, i was talking about how we will use this.
now create one button on your aspx and on it's postback event try to use the code provided below.

string[] selectedCountries= ListBox1.ToListArray<string>();

you will find that not only your Listbox control knows that who is ToListArray<T>() method is, it also know that when you will call this method what output it will provide.

Now to test further more.. add another Listbox and populate it with Datetime,
now then only thing you have to change in your code is this

DateTime[] selectedCountries= ListBox1.ToListArray<DateTime>();

Now test it again.
So the conclusion is, that using this new feature of .net we can reduce the effort of reward-less coding and can actually write few usefully code that will be more versatile and reusable.
I hope you guys those who are new to extension methods will able to write more better and reusable codes.
NOTE: If you write anything good , do share with us.
Cheers for now :)

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

755 members

Comments and Discussions

 
-- There are no messages in this forum --