Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods - Decorator Pattern

I was wondering if we can consider extension methods as an implementation of the decorator pattern in C#? as the aim is the same but logic of implementation as well as the conception may differ?

Thanks!

like image 204
Mohtaa Avatar asked Mar 04 '13 21:03

Mohtaa


People also ask

Is extension method a decorator pattern?

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.

What is extension method with example?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is extension method in MVC?

What is extension method? Extension methods in C# are methods applied to some existing class and they look like regular instance methods. This way we can "extend" existing classes we cannot change. Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC.

What is extension method in OOP?

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.


2 Answers

The decorator pattern is usually associated with adding behavior to particular instances of a type independently of other instances. In the case of an extension method it affects all instances of a type which are compiled in the same scope. I'd argue that it's not a part of the decorator pattern.

like image 199
JaredPar Avatar answered Nov 14 '22 04:11

JaredPar


I think you didn't understand the decorator pattern correctly.
It is not about adding new methods. It's about adding new functionality to existing methods.

So, no, Extension methods are not an implementation of the decorator pattern.

like image 35
Daniel Hilgarth Avatar answered Nov 14 '22 03:11

Daniel Hilgarth