I have been playing along with AOP for years, but didnt become 100% satisfied with the solutions.
AOP Frameworks with runtime weaving, like Spring.AOP, cannot change the interface of a class.
With post compile time Frameworks like Postsharp (anyone knows someone else ?) you can.
Check this sample out, it adds INotifyPropertyChanged implementation to your class. -> http://www.postsharp.net/model/inotifypropertychanged
This AOP feature is really great, but you run in troubles very soon...
If you want to access the new Interface within the hosting assembly, you cannot compile,
because the interface is added AFTER compilation.
so you get a "PropertyChanged is not defined"-error.
So you have to ugly workaround this, by seperating the classes into another assembly, so you can use those AOP advantages.
I remember, i ran into the same "Post compile time"-troubles using a T4-Template that generates source code, based on the reflected infos of a assembly. OK so post compile time is sometimes too late...
What i am looking for is a solution, where the source code of the class is parsed via a visual studio user defined tool, und then generates the code in a C# file, in a partial class.
(so all AOP applied classes have to be partial)
So its kind of "Pre-Compile-Time AOP".
This should definitly be possible, and could be done via using NRefactory as Code Parser.
Furthermore, Visual Studio would like this much more, than a post-compile modification.
So this solution eliminates disadvantages of post compile time weavers.
but does not give you all the features of AOP. But together with an AOP-Framework, this should be awsome.
Does anyone know a framework like this, or a discussion ?!
what do you think ?
kind regards, thomas
since you and I have already been corresponding on using SNAP as a viable alternative, I thought I'd post a summary of our discussion here for the benefit of those who are looking for a similar solution.
In short, SNAP provides a runtime AOP framework that doesn't change your code in any way. There's no post-compile step, just runtime interception which is predictable and easy to use.
What your are looking for is pMixins. It's still in beta, but it does exactly what you are looking for: design-time weaving. AOP code is generated into a partial code-behind class so it's available at design-time.
So this means you can do this in one file and the compiler is happy, visual studio is happy, resharper is happy:
Define an interface:
public interface ISomeInterface
{
void SomeMethod();
}
Create an implementation of the interface (I call this a Mixin):
public class SomeInterfaceImplementation : ISomeInterface
{
public void SomeMethod()
{
//implementation
}
}
Define a Target file (which will consume the Mixin):
[pMixin(Mixin = typeof(SomeInterfaceImplementation))]
public partial class Target { }
Let's create a utility class that works with SomeInterface and SomeInterfaceImplementation:
public class Utility
{
public void DoSomeWorkOnSomeInterface(ISomeInterface obj)
{
obj.SomeMethod();
}
public void DoSomeWorkOnImplementation(SomeInterfaceImplementation obj)
{
obj.SomeMethod();
}
}
And now let's see it all work together:
class Program
{
private static void Main(string[] args)
{
//Call the mixed in method
new Target().SomeMethod();
//Target implements ISomeInterface is code-behind
new Utility().DoSomeWorkOnSomeInterface(new Target());
//Target has an implicit conversion operator to
//SomeInterfaceImplementation in code-behind
new Utility().DoSomeWorkOnImplementation(new Target());
}
}
The reason this works is because as soon as you save the file, the pMixins code generator immediately does design-time weaving and updates the code-behind file. It adds the SomeMethod directly to Target, updates Target's class definition to implement ISomeInterface and creates conversion operators.
Disclosure: I am on the pMixins development team.
In the case of PostSharp, you can access an interface introduced at post-compile-time by using the method Post.Cast, which is a kind of cast operator that is verified at post-compile-time. See http://doc.postsharp.net/postsharp-3.0/Content.aspx/PostSharp-3.0.chm/html/M_PostSharp_Post_Cast__2.htm for documentation.
Every so often, I run into a case where I want a collection of classes all to possess similar logic. For example, maybe I want both a Bird and an Airplane to be able to Fly(). If you're thinking "strategy pattern", I would agree, but even with strategy, it's sometimes impossible to avoid duplicating code.
For example, let's say the following apply (and this is very similar to a real situation I recently encountered):
Both Bird and Airplane need to hold an instance of an object that implements IFlyBehavior.
Both Bird and Airplane need to ask the IFlyBehavior instance to Fly() when OnReadyToFly() is called.
Both Bird and Airplane need to ask the IFlyBehavior instance to Land() when OnReadyToLand() is called.
OnReadyToFly() and OnReadyToLand() are private.
Bird inherits Animal and Airplane inherits PeopleMover.
Now, let's say we later add Moth, HotAirBalloon, and 16 other objects, and let's say they all follow the same pattern.
We're now going to need 20 copies of the following code:
private IFlyBehavior _flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
private void OnReadyToLand()
{
_flyBehavior.Land();
}
Two things I don't like about this:
It's not very DRY (the same nine lines of code are repeated over and over again). If we discovered a bug or added a BankRight() to IFlyBehavior, we would need to propogate the changes to all 20 classes.
There's not any way to enforce that all 20 classes implement this repetitive internal logic consistently. We can't use an interface because interfaces only permit public members. We can't use an abstract base class because the objects already inherit base classes, and C# doesn't allow multiple inheritance (and even if the classes didn't already inherit classes, we might later wish to add a new behavior that implements, say, ICrashable, so an abstract base class is not always going to be a viable solution).
What if...?
What if C# had a new construct, say pattern or template or [fill in your idea here], that worked like an interface, but allowed you to put private or protected access modifiers on the members? You would still need to provide an implementation for each class, but if your class implemented the PFlyable pattern, you would at least have a way to enforce that every class had the necessary boilerplate code to call Fly() and Land(). And, with a modern IDE like Visual Studio, you'd be able to automatically generate the code using the "Implement Pattern" command.
Personally, I think it would make more sense to just expand the meaning of interface to cover any contract, whether internal (private/protected) or external (public), but I suggested adding a whole new construct first because people seem to be very adamant about the meaning of the word "interface", and I didn't want semantics to become the focus of people's answers.
Questions:
Regardless of what you call it, I'd like to know whether the feature I'm suggesting here makes sense. Do we need some way to handle cases where we can't abstract away as much code as we'd like, due to the need for restrictive access modifiers or for reasons outside of the programmer's control?
Update
From AakashM's comment, I believe there is already a name for the feature I'm requesting: a Mixin. So, I guess my question can be shortened to: "Should C# allow Mixins?"
The problem you describe could be solved using the Visitor pattern (everything can be solved using the Visitor pattern, so beware! )
The visitor pattern lets you move the implementation logic towards a new class. That way you do not need a base class, and a visitor works extremely well over different inheritance trees.
To sum up:
New functionality does not need to be added to all different types
The call to the visitor can be pulled up to the root of each class hierarchy
For a reference, see the Visitor pattern
Cant we use extension methods for this
public static void OnReadyToFly(this IFlyBehavior flyBehavior)
{
_flyBehavior.Fly()
}
This mimics the functionality you wanted (or Mixins)
Visual Studio already offers this in 'poor mans form' with code snippets. Also, with the refactoring tools a la ReSharper (and maybe even the native refactoring support in Visual Studio), you get a long way in ensuring consistency.
[EDIT: I didn't think of Extension methods, this approach brings you even further (you only need to keep the _flyBehaviour as a private variable). This makes the rest of my answer probably obsolete...]
However; just for the sake of the discussion: how could this be improved? Here's my suggestion.
One could imagine something like the following to be supported by a future version of the C# compiler:
// keyword 'pattern' marks the code as eligible for inclusion in other classes
pattern WithFlyBehaviour
{
private IFlyBehavior_flyBehavior;
private void OnReadyToFly()
{
_flyBehavior.Fly();
}
[patternmethod]
private void OnReadyToLand()
{
_flyBehavior.Land();
}
}
Which you could use then something like:
// probably the attribute syntax can not be reused here, but you get the point
[UsePattern(FlyBehaviour)]
class FlyingAnimal
{
public void SetReadyToFly(bool ready)
{
_readyToFly = ready;
if (ready) OnReadyToFly(); // OnReadyToFly() callable, although not explicitly present in FlyingAnimal
}
}
Would this be an improvement? Probably. Is it really worth it? Maybe...
You just described aspect oriented programming.
One popular AOP implementation for C# seems to be PostSharp (Main site seems to be down/not working for me though, this is the direct "About" page).
To follow up on the comment: I'm not sure if PostSharp supports it, but I think you are talking about this part of AOP:
Inter-type declarations provide a way
to express crosscutting concerns
affecting the structure of modules.
Also known as open classes, this
enables programmers to declare in one
place members or parents of another
class, typically in order to combine
all the code related to a concern in
one aspect.
Could you get this sort of behavior by using the new ExpandoObject in .NET 4.0?
Scala traits were developed to address this kind of scenario. There's also some research to include traits in C#.
UPDATE: I created my own experiment to have roles in C#. Take a look.
I will use extension methods to implement the behaviour as the code shows.
Let Bird and Plane objects implement a property for IFlyBehavior object for an interface IFlyer
public interface IFlyer
{
public IFlyBehavior FlyBehavior
}
public Bird : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
public Airplane : IFlyer
{
public IFlyBehaviour FlyBehavior {get;set;}
}
Create an extension class for IFlyer
public IFlyerExtensions
{
public void OnReadyToFly(this IFlyer flyer)
{
flyer.FlyBehavior.Fly();
}
public void OnReadyToLand(this IFlyer flyer)
{
flyer.FlyBehavior.Land();
}
}
I'd like to override a class method without inheriting the base class because it'd take a lot of time and modifications and, therefore, more and more tests. It's like this:
class TestClass{
public void initialMethod(){
...
}
}
And somewhere on the code, I'd like to do something like this:
public testMethod()
{
return;
}
test(){
changeMethod(TestClass.initialMethod, testMethod);
}
And this changeMethod function would override the TestClass initialMethod so that it'd call testMethod instead.
Inheriting and overriding the method using normal practices is not an option, as this class A is a graphic component and, inhereting it (and changing it) would break lots of code.
Edit: We don't have the base code for the TestClass, so it's not an option to modify the code there defining the initialMethod as a delegate.
Edit 2: Since this is a graphical component, the designer added a lot of code automatically. If I were to inherit this code, I would have to replace all code added by the designer. That's why I wouldn't like to replace this component.
You need the Strategy pattern.
Main steps:
Create an interface with ie. Do() signature
Your initialMethod() should call a strategy.Do(), where strategy is type of your interface
Create a class that implements this interface. Do() is your testmethod now.
Inject into your main class an instance of this class
If the job it's not so big (let's say just a color replacement or something) then I agree with Jhonny D. Cano's solution with C# (anonymous)delegates.
Edit (after edit 2)
May - just as proof-of-concept - you should inherit the class and replace all references from base class to this new. Do this, and nothing else. If it works, you can think about the next steps (new methods or delegates etc.)
You need only a new checkout from your version control system, and if it maybe fails you can abandon it. It's worth trying.
Perhaps you can do it as a delegate.
class TestClass {
public Action myAction;
public void initialMethod(){
...
}
initialMethod
public TestClass() {
myAction = initialMethod;
}
}
and then on TestMethod
public testMethod()
{
return;
}
test() {
testClassInstance.myAction = testMethod;
}
I think your best bet might be to use a AOP framework like LinFu. There's a codeproject article explaining it:
Introducing LinFu, Part VI: LinFu.AOP – Pervasive Method Interception and Replacement for Sealed Types in Any .NET Language
If 'TestClass' is something you defined, you could replace the 'initialMethod' definition with a property and delegate which can then be set to any method with a given signature. (Even anonymous ones.)
class TestClass {
Action _myMethod;
Action MyMethod {
get { return _myMethod; }
set { _myMethod = value; }
}
var tc = new TestClass()
tc.MyMethod = () -> Console.WriteLine("Hello World!");
tc.MyMethod()
The above code is untested.
The short and simple answer is: if you can't adjust the base TestClass code, no, there's no way you can modify the class to replace a method by another. Once we started doing stuff like that, we'd be in a completely different kind of language, like JavaScript.
The longer answer is: it depends on who is calling the replaced method.
If it's other classes, see if you can't implement a Proxy in between them and the unmodifiable concrete class. Whether this is doable depends on whether that class implements interfaces, or is its own interface.
If it's the class itself, then your only option is to decompile and modify the class, at design time using Reflector (or equivalent tools), or at runtime using Reflection.Emit. However, you'd have to be hurting pretty badly to go this route, as it's sure to be painful and brittle.
Unfortunately you still haven't explained what you are trying do and why. Replacing methods on the go is powerful stuff in the languages that permit it directly... There might be mocking libraries that can be twisted sufficiently far to do the reflection stuff, but then you'd be skating on thin ice.
If you don't have the code use Extension Methods.
public void doSmth(this objectYOUWANT arg)
{
//Do Something
}
Here you use the principle Closed for Modification Open for Extension.
This will add functionality to the library you don't have the source code. It's very clean to do it this way.
Edition:
In FrameWork 3.5 there is something new called Extension Methods. These kind of methods adds functionality to a closed Assembly letting you Extend in functionality a closed dll/assembly.
To use this for example you have a dll that you import, that is called Graphics.dll (you have the reference on your project)
First of all you shoud create a new static class called for example Extension:
public static class Extensions
{
}
Second, you want to add extra functionality to a class contained in Graphics.dll named ChartGraph. You will do this:
public static class Extensions
{
public static void draw(this ChartGraph g)
{
// DO SOMETHING
}
}
Third, when you instantiate a new object from the graphics.dll you now will have the new method you have created:
ChartGraph myG = new ChartGraph();
myG.draw();
As you can see there you have added new functionality without much effort without recompiling the dll, this is good if you don't have the source code.
I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.
Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?
Well you could do some really messy code involving #if - i.e. in DEBUG it is virtual (for the designer), but in RELEASE it is abstract. A real pain to maintain, though.
But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a NotImplementedException).
Of course, your unit tests will check that the methods have been implemented, yes? ;-p
Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:
[Test]
public void TestFoo() {
ActualTest<Foo>();
}
[Test]
public void TestBar() {
ActualTest<Bar>();
}
static void ActualTest<T>() where T : SomeBaseClass, new() {
T obj = new T();
Assert.blah something involving obj
}
You could use the reference to implementation idiom in your class.
public class DesignerHappy
{
private ADesignerHappyImp imp_;
public int MyMethod()
{
return imp_.MyMethod()
}
public int MyProperty
{
get { return imp_.MyProperty; }
set { imp_.MyProperty = value; }
}
}
public abstract class ADesignerHappyImp
{
public abstract int MyMethod();
public int MyProperty {get; set;}
}
DesignerHappy just exposes the interface you want but forwards all the calls to the implementation object. You extend the behavior by sub-classing ADesignerHappyImp, which forces you to implement all the abstract members.
You can provide a default implementation of ADesignerHappyImp, which is used to initialize DesignerHappy by default and expose a property that allows you to change the implementation.
Note that "DesignMode" is not set in the constructor. It's set after VS parses the InitializeComponents() method.
I know its not quite what you are after but you could make all of your stubs in the base class throw the NotImplementedException. Then if any of your subclasses have not overridden them you would get a runtime exception when the method in the base class gets called.
The Component class contains a boolean property called "DesignMode" which is very handy when you want your code to behave differently in the designer than at runtime. May be of some use in this case.
As a general rule, if there's no way in a language to do something that generally means that there's a good conceptual reason not to do it.
Sometimes this will be the fault of the language designers - but not often. Usually I find they know more about language design than I do ;-)
In this case you want a un-overridden virtual method to throw a compile time exception (rather and a run time one). Basically an abstract method then.
Making virtual methods behave like abstract ones is just going to create a world of confusion for you further down the line.
On the other hand, VS plug in design is often not quite at the same level (that's a little unfair, but certainly less rigour is applied than is at the language design stage - and rightly so). Some VS tools, like the class designer and current WPF editors, are nice ideas but not really complete - yet.
In the case that you're describing I think you have an argument not to use the class designer, not an argument to hack your code.
At some point (maybe in the next VS) they'll tidy up how the class designer deals with abstract classes, and then you'll have a hack with no idea why it was coded that way.
It should always be the last resort to hack your code to fit the designer, and when you do try to keep hacks minimal. I find that it's usually better to have concise, readable code that makes sense quickly over Byzantine code that works in the current broken tools.
To use ms as an example...
Microsoft does this with the user control templates in silverlight. #if is perfectly acceptable and it is doubtful the the tooling will work around it anytime soon. IMHO
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object.
He brought up "Why not just add a method to your own class?" We've been going round and round (in a good way). My general response is that it is another tool in the toolbelt, and his response is it is a useless waste of a tool... but I thought I'd get a more "enlightened" answer.
What are some scenarios that you've used extension methods that you couldn't have (or shouldn't have) used a method added on to your own class?
The only advantage of extension methods is code readability. That's it.
Extension methods allow you to do this:
foo.bar();
instead of this:
Util.bar(foo);
Now there are a lot of things in C# that are like this. In other words there are many features in C# that seem trivial and don't have great benefit in and of themselves. However once you begin combining these features together you begin to see something just a bit bigger than the sum of its parts. LINQ benefits greatly from extension methods as LINQ queries would be almost unreadable without them. LINQ would be possible without extension methods, but not practical.
Extension methods are a lot like C#'s partial classes. By themselves they are not very helpful and seem trivial. But when you start working with a class that needs generated code, partial classes start to make a lot more sense.
I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense.
I have a format provider to format a file size. To use it I need to write:
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize));
Creating an extension method I can write:
Console.WriteLine(fileSize.ToFileSize());
Cleaner and simpler.
Don't forget tooling! When you add an extension method M on type Foo, you get 'M' in Foo's intellisense list (assuming the extension class is in-scope). This make 'M' much easier to find than MyClass.M(Foo,...).
At the end of the day, it's just syntactic sugar for elsewhere-static-methods, but like buying a house: 'location, location, location!' If it hangs on the type, people will find it!
Two more benefits of extension methods that i have come across:
A fluent interface can be encapsulated in a static class of extension methods, thereby achieving a separation of concerns between the core class and it's fluent extensions; I've seen that achieve greater maintainability.
Extension methods can be hung off of interfaces, thereby allowing you to specify a contract (via an interface) and an associated series of interface-based behaviors (via extension methods), again offering a separation of concerns. An example are the Linq extension methods like Select(...), Where(...), etc. Hung off the IEnumerable<T> interface.
Some of the best uses I had for extension methods is the ability to:
Extend functionality on third party objects (whether commercial or internal to my company but managed by a separate group), which in many cases will be marked as sealed.
Create default functionality for interfaces without having to implement an abstract class
Take for example, IEnumerable<T>. While it is rich in extension methods, I found it annoying that it did not implement a generic ForEach method. So, I made my own:
public void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach ( var o in enumerable )
{
action(o);
}
}
Voila, all my IEnumerable<T> objects regardless of implementing type, and whether or not I wrote it or someone else did now have a ForEach method by adding an appropriate "using" statement in my code.
One of the great reasons for using extension methods is LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure.
There are plenty of answers about the advantages of extensions methods; how about one addressing the disadvantages?
The biggest disadvantage is that there's no compiler error or warning if you have a regular method and an extension method with the same signature in the same context.
Suppose you create an extension method applying to a particular class. Then later someone creates a method with an identical signature on that class itself.
Your code will compile, and you may not even get a runtime error. But you're no longer running the same code as before.
Fluent Interfaces and Context Sensitivity as demonstrated by Greg Young on CodeBetter
I would like to support the other answers here that mention improved code readability as an important reason behind extension methods. I'll demonstrate this with two aspects of this: method chaining vs. nested method calls, and cluttering of a LINQ query with meaningless static class names.
Let's take this LINQ query as an example:
numbers.Where(x => x > 0).Select(x => -x)
Both Where and Select are extension methods, defined in the static class Enumerable. Thus, if extension methods didn't exist, and these were normal static methods, the last line of code would essentially have to look like this:
Enumerable.Select(Enumerable.Where(numbers, x => x > 0), x => -x)
See how much nastier that query just got.
Second, if you now wanted to introduce your own query operator, you would naturally have no way of defining it inside the Enumerable static class, like all the other standard query operators, because Enumerable is in the framework and you have no control over that class. Therefore, you'd have to define your own static class containing extension methods. You might then get queries such as this one:
Enumerable.Select(MyEnumerableExtensions.RemoveNegativeNumbers(numbers), x => -x)
// ^^^^^^^^^^^^^^^^^^^^^^
// different class name that has zero informational value
// and, as with 'Enumerable.xxxxxx', only obstructs the
// query's actual meaning.
My personal argument for Extension methods is, they fit very well into an OOP design:
consider the simple method
bool empty = String.IsNullOrEmpty (myString)
in comparison to
bool empty = myString.IsNullOrEmpty ();
There are heaps of great answers above about what extension methods let you do.
My short answer is - they nearly eliminate the need for factories.
I'll just point out that they are not a new concept and one of the biggest validations of them is that they are a killer feature in Objective-C (categories). They add so much flexibility to framework-based development that NeXT had NSA and Wall Street financial modelers as major users.
REALbasic also implements them as extends methods and they have been of similar use there simplifying development.
Its true that you can add your (extension) method directly into your class. But not all classes are written by you. Classes from the core library or third party libraries are often closed and it would be impossible to get the syntatic sugar without extension methods. But remember, extension methods are just like (static) standalone methods in eg. c++
Extension methods can also help keep your classes and class dependencies clean. For instance, you may need a Bar() method for the Foo class everywhere Foo is used. However, you may want a .ToXml() method in another assembly and only for that assembly. In that case, you can add the necessary System.Xml and/or System.Xml.Linq dependencies in that assembly and not in the original assembly.
Benefits: dependencies in your defining class assembly is reduced to only the bare necessities and other consuming assemblies will be prevented from using the ToXml() method. See this PDC presentation for further reference.
I agree that extension methods increases readability of code, but it's really nothing else than static helper methods.
IMO using extension methods for adding behaviour to your classes can be:
Confusing:
Programmers might believe that methods are a part of the extended type, thus not understanding why the methods are gone when the extension-namespace isn't imported.
An antipattern:
You decide to add behaviour to types in your framework using extension methods, then shipping them off to some person which into unit testing. Now he's stuck with a framework containing a bunch of methods he can't fake.
Extension methods are really the .NET incorporation of the "Introduce Foreign Method"refactor from Martin Fowler's Book (down to the method signature). They come with basically the same benefits and pitfalls. In the section on this refactor he says that they're a work-around for when you can't modify the class that should really own the method.
I mainly see extension methods as an admission that perhaps they shouldn't have disallowed free functions.
In the C++ community, it is often considered good OOP practice to prefer free nonmember functions over members, because these functions don't break encapsulation by gaining access to private members they don't need. Extension methods seem to be a roundabout way to achieve the same thing. That is, a cleaner syntax for static functions which don't have access to private members.
Extension methods are nothing more than syntactic sugar, but I don't see any harm in using them.
Intellisense on the object itself instead of having to call some ugly utility function
For conversion functions, can change "XToY(X x)" to "ToY(this X x)" which results in pretty x.ToY() instead of ugly XToY(x).
Extend classes you have no control over
Extend functionality of classes when its undesirable to add methods to the classes themselves. For example, you can keep business objects simple and logic-free, and add specific business logic with ugly dependencies in extension methods
I use them to reuse my object model classes. I have a bunch of classes that represent objects that I have in a database. These classes are used in the client side only to display the objects so the basic usage is accessing properties.
public class Stock {
public Code { get; private set; }
public Name { get; private set; }
}
Because of that usage pattern I don't want to have business logic methods in these classes, so I make every business logic to be an extension method.
public static class StockExtender {
public static List <Quote> GetQuotesByDate(this Stock s, DateTime date)
{...}
}
This way I can use the same classes for business logic processing and for user interface displaying without overloading the client side with unnecessary code.
One interesting thing about this solution it's that my object model classes are dynamic generated using Mono.Cecil, so it would be very difficult to add business logic methods even if I wanted. I have a compiler that reads XML definition files and generate these stubs classes representing some object I have in the database. The only approach in this case is to extend them.
It allows C# to better support dynamic languages, LINQ and a dozen other things. Check out Scott Guthrie's article.
In my last project, I used extension method to attach Validate() methods to business objects. I justified this because the business objects where serializable data transfer objects and will be used in diffrent domains as they where general ecommerce entities such as product, customer, merchant etc. Well in diffrent domains the business rules may be diffrent as well so I encapsulated my late bound validation logic in a Validate method attahced to the base class of my data transfer objects. Hope this makes sense :)
One case where extension methods were quite useful was in a client-application that uses ASMX web services. Due to the serialization, the return types of web methods do not contain any methods (only the public properties of these types are available on the client).
Extension methods allowed use to add functionality (on the client-side) to the types returned by web methods without having to create yet another object model or numerous wrapper classes on the client-side.
Extension methods can be used to create a kind of mixin in C#.
This, in turn, provides better separation of concerns for orthogonal concepts. Take a look at this answer as an example.
This can also be used to enable roles in C#, a concept central to the DCI architecture.
Also remember that extension methods were added as a way to help Linq query to be more readable, when used in their C# style.
These 2 affectations are absolutely equivalent, yet the first is far more readable (and the gap in readibility would of course increase with more methods chained).
int n1 = new List<int> {1,2,3}.Where(i => i % 2 != 0).Last();
int n2 = Enumerable.Last(Enumerable.Where(new List<int> {1,2,3}, i => i % 2 != 0));
Note that the fully qualified syntax should even be :
int n1 = new List<int> {1,2,3}.Where<int>(i => i % 2 != 0).Last<int>();
int n2 = Enumerable.Last<int>(Enumerable.Where<int>(new List<int> {1,2,3}, i => i % 2 != 0));
By chance, the type parameters of Where and Last don't need to be explicitely mentioned as they can be infered thanks to the presence of the first parameter of these two methods (the parameter which is introduced by the keyword this and make them extension methods).
This point is obviously an advantage (among others) of the extension methods, and you can take benefit from it in every similar scenario where method chaining is involved.
Especially, it is the more elegant and convincing way I found to have a base class method invokable by any subclass and returning a strongly typed reference to this subclass (with the subclass type).
Example (ok, this scenario is totally cheesy) : after a good night, an animal opens the eyes then gives a cry; every animal opens the eyes the same way, whereas a dog barks and a duck kwaks.
public abstract class Animal
{
//some code common to all animals
}
public static class AnimalExtension
{
public static TAnimal OpenTheEyes<TAnimal>(this TAnimal animal) where TAnimal : Animal
{
//Some code to flutter one's eyelashes and then open wide
return animal; //returning a self reference to allow method chaining
}
}
public class Dog : Animal
{
public void Bark() { /* ... */ }
}
public class Duck : Animal
{
public void Kwak() { /* ... */ }
}
class Program
{
static void Main(string[] args)
{
Dog Goofy = new Dog();
Duck Donald = new Duck();
Goofy.OpenTheEyes().Bark(); //*1
Donald.OpenTheEyes().Kwak(); //*2
}
}
Conceptually OpenTheEyes should be an Animal method, but it would then return an instance of the abstract class Animal, which doesn't know specific subclass methods like Bark or Duck or whatever. The 2 lines commented as *1 and *2 would then raise a compile error.
But thanks to the extension methods, we can have kind of a "base method which knows the subclass type on which it is called".
Note that a simple generic method could have done the job, but in a far more awkward way :
public abstract class Animal
{
//some code common to all animals
public TAnimal OpenTheEyes<TAnimal>() where TAnimal : Animal
{
//Some code to flutter one's eyelashes and then open wide
return (TAnimal)this; //returning a self reference to allow method chaining
}
}
This time, no parameter and thus no possible return type inference. The call can be nothing other than :
Goofy.OpenTheEyes<Dog>().Bark();
Donald.OpenTheEyes<Duck>().Kwak();
... which can weigh the code a lot if more chaining is involved (especially knowing that the type parameter will always be <Dog> on Goofy's line and <Duck> on Donald's one...)
I have only one word to tell about it: MAINTAINABILITY this is the key for extension methods use
I think extension methods help to write code that is clearer.
Instead of putting a new method inside your class, as your friend suggested, you put it in the ExtensionMethods namespace. In this way you maintain a logical sense of order to your class. Methods that don't really directly deal with your class won't be cluttering it up.
I feel extension methods make your code clearer and more appropriately organized.
It allows your editor/IDE do auto-complete suggestion smart.
I love them for building html.
Frequently there are sections that are used repeatedly, or generated recursively where a function is useful but would otherwise break the flow of the program.
HTML_Out.Append("<ul>");
foreach (var i in items)
if (i.Description != "")
{
HTML_Out.Append("<li>")
.AppendAnchor(new string[]{ urlRoot, i.Description_Norm }, i.Description)
.Append("<div>")
.AppendImage(iconDir, i.Icon, i.Description)
.Append(i.Categories.ToHTML(i.Description_Norm, urlRoot)).Append("</div></li>");
}
return HTML_Out.Append("</ul>").ToString();
There are also situations where an object needs custom logic to be prepared for HTML output- extension methods let you add this functionality without mixing presentation and logic within the class.
I've found extension methods are useful to match nested generic arguments.
That sounds a bit wierd - but say we have a generic class MyGenericClass<TList>, and we know that TList itself is generic (e.g. a List<T>), I don't think that there's a way to dig out that nested 'T' from the List without either extension methods or static helper methods. If we only have static helper methods at our disposal, it's (a) ugly, and (b) will force us to move functionality that belongs in the class to an external location.
e.g. to retrieve the types in a tuple and convert them into a method signature we can use extension methods:
public class Tuple { }
public class Tuple<T0> : Tuple { }
public class Tuple<T0, T1> : Tuple<T0> { }
public class Caller<TTuple> where TTuple : Tuple { /* ... */ }
public static class CallerExtensions
{
public static void Call<T0>(this Caller<Tuple<T0>> caller, T0 p0) { /* ... */ }
public static void Call<T0, T1>(this Caller<Tuple<T0, T1>> caller, T0 p0, T1 p1) { /* ... */ }
}
new Caller<Tuple<int>>().Call(10);
new Caller<Tuple<string, int>>().Call("Hello", 10);
That said, I'm not sure where the dividing line should be - when should a method be an extension method, and when should it be a static helper method? Any thoughts?
I have input zones on my screen, and all must implement a standard behavior whatever their exact types are (textboxes, checkboxes, etc.). They cannot inherit a common base class as each type of input zone already derives from a specific class (TextInputBox, etc.)
Maybe by going up in the inheritance hierachy I could find a common ancestor like say WebControl, but I didn't develop the framework class WebControl and it doesn't expose what I need.
With the extension method, I can :
1) extend the WebControl class, and then obtain my unified standard behavior on all my input classes
2) alternatively make all my classes derive from an interface, say IInputZone, and extend this interface with methods. I will now be able to call extensions methods related to the interface on all my input zones. I thus achieved a kind of multiple inheritance since my input zones already derived from multiple base classes.
There are so many great examples of extension methods..especially on IEnumerables as posted above.
e.g. if I have an IEnumerable<myObject> I can create and extension method for IEnumerable<myObject>
mylist List<myObject>;
...create the list
mylist.DisplayInMyWay();
Without Extension Methods would have to call:
myDisplayMethod(myOldArray); // can create more nexted brackets.
another great example is creating a Circular Linked List in a flash!
I can' take credit for it!
circlular linked list using extension Methods
Now combine these and using extension Methods code reads as follows.
myNode.NextOrFirst().DisplayInMyWay();
rather than
DisplayInMyWay(NextOrFirst(myNode)).
using Extension Methods It is neater and easier to read and more object orientated.
also very close to :
myNode.Next.DoSomething()
Show that to your collegue! :)