Back to list
Views:   10.1K
Replies:  1
Archived
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;
        }

    }

 

Amit Malina, Sep 21, 2013
Reply 1
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

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