Extension Method


Extension Method :

  1. This is concept is meant for extending the methods of a class.
  2. There are two ways to extend a class:
    • Inheritance
    • Extension Methods
  3. As you know already in "inheritance", you can extend the features of a class by defining derived class.
  4. But in this "inheritance" feature, you are creating two classes (base class and derived class).
  5. But, if you want to add a method to an existing class, that is accessible with the objects of the same class, it is not possible in inheritance". But it is possible using Extension Methods".
  6. Conclusion : This feature allows you to add one or more new methods to the same class, without changing the definition of that particular class.
  7. This is more useful, when you want to add more methods to a pre-defined class.

Implementation :

  • When you want to implement this concept practically, simply take a new static class first.
  • In this static class, write a static method, with the required name.
  • In that method, the first argument should be like this: this classname argumentname
  • Here, in place of "classname", specify the class name, for which you want to write the extension method.
  • Then the argument name acts as this" pointer in the code.
  • Note : Even though it is defined as a ―static method‖ it is accessible as a non-static method from the object of the source class.
    Syntax :
    
     public static return_type method_name(this class_name arg, )
      {
        //some code
      }
    
    
  • Limitation : You can‘t add a static method" for an existing class.

C# Coding on Extension Method :


StringExtension.cs
==================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

 namespace ExtensionMethodsDemo
  {
    static class StringExtension
     {
      public static string Reverse(this String str)
       {
        char[] ch = str.ToCharArray();
        Array.Reverse(ch);
        string mystr = new String(ch);
        return (mystr);
       }
     }
    }
 
Program.cs
==========

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

 namespace ExtensionMethodsDemo
  {
   class Program
    {
     static void Main(string[] args)
      {
       string s = "abcdefghijklmnopqrstuvwxyz";
       Console.WriteLine(s.Reverse()); 
       Console.Read();
      }
    }
  }
0 Komentar untuk "Extension Method"

Back To Top