RSS

Example showing Extension Methods in C#

Sun, Jan 3, 2010

Programming, Tutorials

Extension Method is really a cool stuff. We can simply add the additional method to any object without knowing anything about that object.Let’s say we want a method for string object which will reverse the string then you can choose extension method to do the thing.

Start writing Extension method:

static class Extension
    {
        public static string Reverse(this String input)
        {
            char[] inputchar = input.ToCharArray();
            for (int i = 0; i < input.Length / 2; i++)
            {
                inputchar[i] ^= inputchar[input.Length - 1 - i];
                 inputchar[input.Length - 1 - i]^=inputchar[i] ;
                 inputchar[i] ^= inputchar[input.Length - 1 - i];
            }
            return new string(inputchar);
        }
    }

Note:
class should be static, Method should be public static and the object on which the method to be added should be passed as parameter preceding by keyword this.

Now you can start to use this method as

class Program
    {
        static void Main(string[] args)
        {
            string s = "ujwal";
            Console.WriteLine(s.Reverse());
        }
    }

I have done extensive use of Extension method while going through Asp.Net MVC project.

Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Related Posts:

,

This post was written by:

Ujwal Manandhar - who has written 4 posts on eXclusiveMinds.


Contact the author

4 Comments For This Post

  1. eXclusiveMinds Says:

    Thank you ujwal for cool stuff.

  2. Danuta Maccord Says:

    Thank you for the well-written article. I liked it. You have a very nice site.

  3. chota Says:

    Don’t we need to add reference to our program? how will it recognize the extension method until there is some way to point out which one to use?

  4. Ujwal Manandhar Says:

    Thanks for your valuable comments.
    @chota: yes it’s true, the class containig the extension method should be refrenced. Here in the example Extension class is supposed to be in the same namespace.

Leave a Reply

You must be logged in to post a comment.