Click here to Skip to main content
15,891,372 members
Articles / Programming Languages / C#
Tip/Trick

Extension Methods

Rate me:
Please Sign up or sign in to vote.
3.75/5 (4 votes)
11 Nov 2010CPOL 19.4K   2   4
Extension Methods




What is Extesion Methods ?





Method allow programmer to "add" methods to existing types without creating a new derived type, recompiling, or by modifying the original type. Methods are static methods they are called as if they were instance methods on the extended type.








Example : 








C#
public static class Utilities
{
   public static string encryptString(this string str)
  {
      System.Security.Cryptography.MD5CryptoServiceProvider x = new                      System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(str);
            data = x.ComputeHash(data);
            return System.Text.Encoding.ASCII.GetString(data);
    }
}







How to call Extension Method ?





As you can see in below image IDE intelligence shows the extension method with the down arrow when you want to call on the given datatype.  







As you can see in above example I have created a function encryptString to encrypt the string which is having sensitive data and want to store its in encrypted form in database.

So the common use of extenstion method is when you are creating utility functions in your project which can extend functionality of the existing .net type or of the existing dll available in your project.

License

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


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralReason for my vote of 4 good screen shot and clean explanati... Pin
Member 345669117-Nov-10 0:54
Member 345669117-Nov-10 0:54 
GeneralReason for my vote of 3 Grammar. Only one example. Pin
Oshtri Deka15-Nov-10 2:53
professionalOshtri Deka15-Nov-10 2:53 
GeneralIntelligence vs. IntelliSense Pin
johannesnestler19-Nov-10 3:25
johannesnestler19-Nov-10 3:25 
AnswerRe: Intelligence vs. IntelliSense Pin
rajeshthedotnetguy21-Jul-11 19:12
rajeshthedotnetguy21-Jul-11 19:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.