2
Reply

Extension Method Definition And Simple Example

Annathurai Subbaiah

Annathurai Subbaiah

Feb 19 2010 7:33 AM
5k

Extension Method Definition:
1.It allows you to add new method to the existing class without modifying the code, recompiling.
2.It is special kind of static method but they are called using instance method syntax.
3.Extension method class should be static keyword and Method should have this keyword to invoke.
4.Extension method are only in scope when you explicitly import the namespace into your source code with 'using' directive.
Example of Extension Method:
namespace Extensionmethods
{
    public static class ExtensionMethod
    {
        public static string Reverse(this string strReverse)
        {
            char[] reverseArray = new char[strReverse.Length];
            int len = reverseArray.Length - 1;
            for (int i = 0; i <= len; i++)
            {
                reverseArray[i] = strReverse[len - i];
            }
            return new string(reverseArray);
        }
    }
}
 
Calling Extension Method:
 public void Page_Load(object sender, EventArgs e)
    {
        string strName = "annathurai";
        string strResult = strName.Reverse();

Attachment: Extension Method.zip

Answers (2)
Next Recommended Forum