Back to list
Views:   10.1K
Replies:  1

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,
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);
                res = str;

            return res;



Amit Malina, Sep 21, 2013
Reply 1

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

Jack Poorte, Sep 22, 2013
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.