Home  /  Questions  /  Question



50   50
Sep 21, 2013


Question on Extension methods vs the Decorator Pattern

Hi All,

Recently i was thinking about the Decorator Pattern using C# ,
As I understand  from .NET  2 there is a Decorator pattern as part of .NET language .

For example: 
I added Substring function as part of String class and as you can see at the picture below, .NET recognize 
the new function as "part" of String class.

I was just wondering why sample of Decorator Pattern "NET optimized sample code" section doesn't give this option?
I used to work with the this Pattern when I wrote classic VB (at the 90's).  

I would like to get comments on this issue.

Have a nice weekend,
Amit. 
class Program
    {
        static void Main(string[] args)
        {

            String s = "Hello World";

            s = s.SubString(0, 4);
        }
    }


    public static class StringExtetion 
    {
        public static String SubString(this string str, int from , int maxlength)
        {
            String res = String.Empty;

            if (str != String.Empty && str.Length > (from + maxlength))
                res = str.Substring(from, maxlength);
            else
                res = str;

            return res;
        }

    }

 




508   99.9
Sep 22, 2013
Amit: 

Great question. However, extension methods are not replacements for Decorators.  Here is why: 

Extension methods are static methods that are compiled in and are not changeable at runtime. 
The Decorator allows you to wrap a class inside another class and change its behavior (dynamically) -- something you couldn't do with a static extension method.

Hope this helps. 
Jack Poorte

 1 comment
 
Thanks ! --- Amit Malina  Sep 24, 2013