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.
No comments:
Post a Comment