Archive for category Design Patterns

Extension Methods (Decorator Pattern Microsoft Way)

With traditional object oriented development, extending objects (classes) is normally achieved by deriving class from base class and placing extra functionality there.

but some times you are not allowed to extend classes (marked not extendible sealed/NotInheritable, as a result there is no way to extend these classes although you can still use some patterns like decorator to achieve the goal but the hard way.

A good example of this is System.String class as its non extendible

To solve this issue the easy way Microsoft implemented in the form of Extension Methods in Dotnet framework 3.5, it lets you extend any existing type’s functionality even when a type is non extendible

How to create Extension Method

lets create a sample for Extension Methods, we will extend String class and will provide 3 extension methods namely

  • Is Valid (just verifies instant of the string returns true/false
  • ToString (will talk about this one later)
  • ToAlternateString (this will return a simple string)

lets start (I am using c# for this example):

  1. Create a C# console application
  2. Create a new class as in my example I have named it “Extensions” with the namespace “StringExtensions” and mark the class as “static”
  3. Create the 3 methods we talked about above and mark them as static too.
  4. now here comes the real trick the first parameter of the method specifies the type that the method operates on; it must be preceded with the this modifier e.g. in my case
       1: public static bool IsValid(this string value)

    you can see that in the parameter I have added this and after that the objecttype which in my case is string, it ensures that this method will work only on string type objects.
    Do note that Extension Methods can not access any private data in the extended class.

  5. here is my Extensions class
       1: namespace StringExtensions
       2: {
       3:     public static class Extenions
       4:     {
       5:         /// <summary>
       6:         /// to validate if value is valid or not just an alternate implementation of isnullorempty
       7:         /// </summary>
       8:         /// <param name="value"></param>
       9:         /// <returns></returns>
      10:         public static bool IsValid(this string value)
      11:         {
      12:             return string.IsNullOrEmpty(value);
      13:         }
      14:  
      15:         /// <summary>
      16:         /// Extending string method to prove that it always calls base
      17:         /// </summary>
      18:         /// <param name="obj"></param>
      19:         /// <returns></returns>
      20:         public static string ToString(this string obj)
      21:         {
      22:             return "To String method Extended";
      23:         }
      24:  
      25:  
      26:         /// <summary>
      27:         /// Writing my string method
      28:         /// </summary>
      29:         /// <param name="obj"></param>
      30:         /// <returns></returns>
      31:         public static string ToAlternateString(this string obj)
      32:         {
      33:             return "My alternate String method called";
      34:         }
      35:     }
      36: }
  6. here is my Program class
       1: using System;
       2: using StringExtensions;
       3:  
       4: namespace Extension_Methods
       5: {
       6:     class Program
       7:     {
       8:         static void Main(string[] args)
       9:         {
      10:             string obj=null;
      11:             Console.WriteLine(String.Format("Calling extended method IsValid"));
      12:             Console.WriteLine(String.Format("Object is Null={0}", obj.IsValid()));
      13:             Console.WriteLine();
      14:  
      15:             Console.WriteLine(String.Format("Intializing string object with value obj=string"));
      16:             obj="string";
      17:             Console.WriteLine(String.Format("Value of String Object is {0}", obj.ToString()));
      18:             Console.WriteLine();
      19:  
      20:             Console.WriteLine(String.Format("Calling Alternate string Value method"));
      21:             Console.WriteLine(String.Format("Value of String Object is {0}", obj.ToAlternateString()));
      22:             Console.ReadKey();
      23:         }
      24:     }
      25: }
  7. Now execute the program

you will notice that Isvalid and ToAlternateString methods are working fine but “ToString()” method we extended it is not working as our output was supposed to be “To String method Extended” but in this case its the actual value.

That is the one of the beauty of Extension Methods “An extension method will never be called if it has the same signature as a method defined in the type/Instance.

Source Code:

 http://cid-61e3517bd730d0c7.skydrive.live.com/embedrowdetail.aspx/Public/ExtensionMethods.zip

there are some other topics related to this which I will cover later.

 

kick it on DotNetKicks.com  Shout it

Advertisements

Leave a comment