Wednesday, July 25, 2012

C#.net - Extension Method in C#.net

Another cool feature of C# 3.0 is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type.in Short Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.


Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.



An extension method is a static method of a static class, where the this modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.


Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.


An extension method uses the 'this' keyword in its parameter list. It must be located in a static class.



Step 1
Create a Console Application and give the solution name as ConExtensionMethod.


Step 2
Extension method behavior is similar to that of static methods. You can declare them only in static classes. To declare an extension method, you specify the keyword 'this' as the first parameter of the method.here i am converting Arraylist to Generic List Program.,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConExtensionMethod
{
    public static class Extension
    {
        #region Methods

        /// <summary>
        /// Convert Array List into List
        /// </summary>
        /// <typeparam name="T">Specify the Generic Type</typeparam>
        /// <param name="ArrayListObj">this Array List Object</param>
        /// <returns>Generic List</returns>
        public static List<T> ToList<T>(this ArrayList ArrayListObj)
        {
            try
            {
                // Create Object of generic List Object.
                List<T> ListObj = new List<T>();

                // get Data from ArrayList and add in Generic List Object.
                foreach (T Obj in ArrayListObj)
                {
                    ListObj.Add(Obj);
                }

                return ListObj;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }


        }

        #endregion
    }
}

This program introduces the static Extensions class and the ToList generic method inside that class. ToList here is a generic extension method; it has a type parameter T.


Step 3
Now add a String data in ArrayList Object.it is look like this
// Create A instance of ArrayList.
                ArrayList ArrayListObj = new ArrayList();

                // Add a sample Data in Arraylist.
                ArrayListObj.Add("Test1");
                ArrayListObj.Add("Test2");
                ArrayListObj.Add("Test3");


Step 4
Use Extension Methods,it is look like this
// Convert ArrayList Data into List Object.
                // Use Extension Method.
                List<String> ListStringObj = ArrayListObj.ToList<String>();

                // Print Data in Console
                foreach (String StringObj in ListStringObj)
                {
                    System.Console.WriteLine(StringObj);
                }

Full Main Function
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Create A instance of ArrayList.
                ArrayList ArrayListObj = new ArrayList();

                // Add a sample Data in Arraylist.
                ArrayListObj.Add("Test1");
                ArrayListObj.Add("Test2");
                ArrayListObj.Add("Test3");

                // Convert ArrayList Data into List Object.
                // Use Extension Method.
                List<String> ListStringObj = ArrayListObj.ToList<String>();

                // Print Data in Console
                foreach (String StringObj in ListStringObj)
                {
                    System.Console.WriteLine(StringObj);
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
        }
    }
}

Note






ArrayList doesn't have ToList method.here i am add ToList Extension Method in Arraylist. 


Output


Click on Image for Better View.

Download
Download Source Code

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete