User Id :    Password :      New Member   Forgot Password  
 
Extension Methods in C#
Description 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.   No. of Views     1001
  Rating     0
Author Pranay Rana   Posted On     16 May 2012
Tags C#    

Sample Code   Download Code

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 :

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.

 

 

About Author

About Author Hey, I am Pranay Rana, working as a Senior Software engineer. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 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 me on my blog - http://pranayamr.blogspot.com/
Pranay Rana
No Photo
 
Country India
Company GMind Solutions
Home Page http://pranayamr.blogspot.com/

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code