Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

Extension Methods is a new feature of the C# language (I think it is called C# 3.0). Extension methods allows you to extend the CLR types. This includes all the types which inherit from the System.Object class. Let's see a small example where I have extended a String to add a new "Reverse" method which gives me the string in reverse.

 public static string Reverse(this string s)
        {
            string r = String.Empty;

            for (int i = s.Length -1; i >= 0; i--)
            {
                r += s[i].ToString();
            }

            return r;            
        }

I am using the Extension methods in a separate class. It is a good idea to keep this separation as Extension methods behaves like Utility or Helper classes for your library. Here is my class.

 public static class ExtensionMethods

Note that the class has to be static.

Now, I can invoke the Reverse method on any of my string variables.

string myString = "something is funny!";
Console.WriteLine(myString.Reverse());     

Here is another example where I created a method "IsPrime" which will act on the numeric types.

        public static bool IsPrime(this int number)
        {          
            for (int i = (2); i < number; i++)
            {
                if (number < 2) return false;

                if ((number % i) == 0)
                {
                    return false;
                }
            }

            return true;
        }

And I can call it like this:

            7.IsPrime();
            2.IsPrime();

I can also have a method ToXml which will work on all CLR types.

 // serialize the object to xml
        public static string ToXml(this object source)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            XmlSerializer xSer = new XmlSerializer(source.GetType());
            xSer.Serialize(sw, source);

            return sb.ToString();
        }

Customer customer = new Customer();

customer.ToXml();

string foo = "Foo";

foo.ToXml();

 

Here is another Extension Method that works on GridView and get all the selected rows:

public static GridViewRow[] GetCheckedRows(this GridView gv,string chkboxId)
        {
            List<GridViewRow> checkedRows = new List<GridViewRow>();

            foreach (GridViewRow row in gv.Rows)
            {
                CheckBox chk = (CheckBox) row.FindControl(chkboxId);

                if (chk != null)
                {
                    if (chk.Checked)
                    {
                        checkedRows.Add(row);
                    }
                }
            }

            return checkedRows.ToArray();
        }

And you can call the above method like this:

GridViewRow[] rows = gvProducts.GetCheckedRows("chkSelect");

 

Although Extension methods are cool you should always use them wisely! Don't mix them up with your domain objects. They can serve a good purpose as Utlity Classes and Helper Methods.

Posted on Monday, December 3, 2007 9:43 AM | Back to top


Comments on this post: Having Fun with Extension Methods :)

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net