CollectionBase vs generics - c#

I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?

Yes, the best classes to look at are in System.Collections.Generic.
I usually use List.
There are two approaches you can use either:
A
public class MyClass
{
public List<MyItem> Items;
}
B
public class MyItemCollection : List<MyItem>
{
}
public class MyClass
{
public MyItemCollection Items;
}
The two approaches only differ very slightly and you only need to use method (B) if you plan on extending the functionality of List.
Here's a link with more info:
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx
With regards to the classes that you've already implemented, you can remove all of the functions which are specified in the IList interface. e.g.
public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); }
This can be removed because List already implements a type safe Add function for you.
See this link for more information:
http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx

Generally, List<T> does most of what you normally want. If you want to customize behaviour, you should inherit from Collection<T> - this has virtual methods so you can tweak behaviour when adding/removing/updating etc. You can't do this with List<T> since there are no (uesful) virtual methods.

I prefer Mark Ingrams A) approach, possibly with a base class you write yourself.
There is another issue with migrating to generics; converting has a tendency to have a certain viral effect. You may find it impossible to stop before you're all the way through. If you THOUGHT you were going to spend a couple of hours doing SOME generics, you'll often find yourself spending several days doing ALL the generics.
You can/should avoid this by giving your new classes operator overloads to/from list
public static implicit operator MyClass(List m)
{
// code to convert from m to MyClass
}
public static explicit operator List(MyClass m)
{
// code to convert from MyClass list
}
These are really just stopgaps. You can use "find usages" on these at any later stage to determine which places have not been fully converted. When all usages are removed, you can delete the casts.
I generally perfer to make the cast from MyClass to List explicit (this is the way you dont want to go) and the other implicit.
The best approach would then normally be to start at the TOP of your layers, close to the presentation layer and work downwards. (This is opposite of what you might think. If you make the cast from MyClass to List implicit it doesnt matter which end you start)

Related

Return array of 'this' in C#

I have a library which contains a class. This class is meant to be extended. It will connect to a database and generate entries of the class which extends it. Now I want to return an array of the type of the extending class. How can I do this ? For example :
public this[] search(string search) {
}
How can I perform this ?
EDIT :
I'm using generics, it's a generic class. Which means I don't have any clue on what the class which will extend mine will be. So no I can't just add the class name before the []...
EDIT 2:
As it has been pointed out, returning an array of this doesn't make any sense (my mistake then). So what I want to do is return an array of the extending class type.
For example :
public abstract class MappingObject {
public ExtendedClassType[] search (string search) {
}
}
Found the solution ._. I'm sorry it was quite simple...
public abstract class MappingObject<T> where T : new() {
public static List<T> search(string search) {
}
}
I'm not entirely sure what you are looking for, but based on a few clues in your question you might want to review something like the following (referred to as the Curiously Recurring Template Pattern):
public abstract class MyBaseClass<T> : where T : MyBaseClass<T>
{
public abstract T[] Search(string search);
}
public class DerivedClass : MyBaseClass<DerivedClass>
{
public override DerivedClass[] Search(string search)
{
return new DerivedClass[0];
}
}
This is possible, but I'm not sure if it is what you are looking for and I'd review to see if this was a good design choice or not, it feels a little leaky.
This particular idea is used in frameworks like CSLA.NET in order to expose to derived class strong references to themselves when inheriting from certain base classes. This is usually a "syntax sugar" thing, and avoids having to cast up a lot just to use things on your own type when retrieving them from base classes. The base class itself still should not understand what types are deriving from it.
Eric Lippert talks about this pattern on his old MS blog. It has its pitfalls and he exposes a manner in which it can be abused. I personally stand by the approach that being aware of these pitfalls and possibilities for abuse is good enough, so long as things are tested I'm happy to use something that might go against guidelines or principles if the case is clear (there isn't enough additional information to understand if it is clear in this particular case). Eric's post ends:
All that said, in practice there are times when using this pattern really does pragmatically solve problems in ways that are hard to model otherwise in C#; it allows you to do a bit of an end-run around the fact that we don't have covariant return types on virtual methods, and other shortcomings of the type system. That it does so in a manner that does not, strictly speaking, enforce every constraint you might like is unfortunate, but in realistic code, usually not a problem that prevents shipping the product.
My advice is to think very hard before you implement this sort of
curious pattern in C#; do the benefits to the customer really outweigh
the costs associated with the mental burden you're placing on the code
maintainers?
The best use of this pattern I have seen left all the recurring parts internal or protected and the public API was left alone.
'this' means this instance of a class, so your code at the minute basically says 'I want to return an array of this instance of MyClass' which doesn't really make sense.
I think you want to say 'I want to return an array of this type of class object'
So you specify the return type of the method as the class name.
public YourClassName[] Search(string search)
{
}
Do you mean,
public class YourClass
{
public T[] Search<T>(string search, Convertor<SearchResult, T> convertor)
{
...
List<SearchResult> results = ...
return results.ConvertAll(convertor).ToArray();
}
}
This way, you delegate the conversion to the caller who will know what type is passed as the generic type parameter.

What is the name of this bad practice / anti-pattern?

I'm trying to explain to my team why this is bad practice, and am looking for an anti-pattern reference to help in my explanation. This is a very large enterprise app, so here's a simple example to illustrate what was implemented:
public void ControlStuff()
{
var listOfThings = LoadThings();
var listOfThingsThatSupportX = new string[] {"ThingA","ThingB", "ThingC"};
foreach (var thing in listOfThings)
{
if(listOfThingsThatSupportX.Contains(thing.Name))
{
DoSomething();
}
}
}
I'm suggesting that we add a property to the 'Things' base class to tell us if it supports X, since the Thing subclass will need to implement the functionality in question. Something like this:
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
if (thing.SupportsX)
{
DoSomething();
}
}
}
class ThingBase
{
public virtual bool SupportsX { get { return false; } }
}
class ThingA : ThingBase
{
public override bool SupportsX { get { return true; } }
}
class ThingB : ThingBase
{
}
So, it's pretty obvious why the first approach is bad practice, but what's this called? Also, is there a pattern better suited to this problem than the one I'm suggesting?
Normally a better approach (IMHO) would be to use interfaces instead of inheritance
then it is just a matter of checking whether the object has implemented the interface or not.
I think the anti-pattern name is hard-coding :)
Whether there should be a ThingBase.supportsX depends at least somewhat on what X is. In rare cases that knowledge might be in ControlStuff() only.
More usually though, X might be one of set of things in which case ThingBase might need to expose its capabilities using ThingBase.supports(ThingBaseProperty) or some such.
IMO the fundamental design principle at play here is encapsulation. In your proposed solution you have encapsulated the logic inside of the Thing class, where as in the original code the logic leaks out into the callers.
It also violates the Open-Closed principle, since if you want to add new subclasses that support X you now need to go and modify anywhere that contains that hard-coded list. With your solution you just add the new class, override the method and you're done.
Don't know about a name (doubt such exists) but think of each "Thing" as a car - some cars have Cruise Control system and others do not have.
Now you have fleet of cars you manage and want to know which have cruise control.
Using the first approach is like finding list of all car models which have cruise control, then go car by car and search for each in that list - if there it means the car has cruise control, otherwise it doesn't have. Cumbersome, right?
Using the second approach means that each car that has cruise control come with a sticker saying "I has cruise control" and you just have to look for that sticker, without relying on external source to bring you information.
Not very technical explanation, but simple and to the point.
There is a perfectly reasonable situation where this coding practice makes sense. It might not be an issue of which things actually support X (where of course an interface on each thing would be better), but rather which things that support X are ones that you want to enable. The label for what you see is then simply configuration, presently hard-coded, and the improvement on this is to move it eventually to a configuration file or otherwise. Before you persuade your team to change it I would check this is not the intention of the code you have paraphrased.
The Writing Too Much Code Anti-Pattern. It makes it harder to read and understand.
As has been pointed out already it would be better to use an interface.
Basically the programmers are not taking advantage of Object-Oriented Principles and instead doing things using procedural code. Every time we reach for the 'if' statement we should ask ourselves if we shouldn't be using an OO concept instead of writing more procedural code.
It is just a bad code, it does not have a name for it (it doesn't even have an OO design). But the argument could be that the first code does not fallow Open Close Principle. What happens when list of supported things change? You have to rewrite the method you're using.
But the same thing happens when you use the second code snippet. Lets say the supporting rule changes, you'd have to go to the each of the methods and rewrite them. I'd suggest you to have an abstract Support Class and pass different support rules when they change.
I don't think it has a name but maybe check the master list at http://en.wikipedia.org/wiki/Anti-pattern knows? http://en.wikipedia.org/wiki/Hard_code probably looks the closer.
I think that your example probably doesn't have a name - whereas your proposed solution does it is called Composite.
http://www.dofactory.com/Patterns/PatternComposite.aspx
Since you don't show what the code really is for it's hard to give you a robust sulotion. Here is one that doesn't use any if clauses at all.
// invoked to map different kinds of items to different features
public void BootStrap
{
featureService.Register(typeof(MyItem), new CustomFeature());
}
// your code without any ifs.
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
thing.InvokeFeatures();
}
}
// your object
interface IItem
{
public ICollection<IFeature> Features {get;set;}
public void InvokeFeatues()
{
foreach (var feature in Features)
feature.Invoke(this);
}
}
// a feature that can be invoked on an item
interface IFeature
{
void Invoke(IItem container);
}
// the "glue"
public class FeatureService
{
void Register(Type itemType, IFeature feature)
{
_features.Add(itemType, feature);
}
void ApplyFeatures<T>(T item) where T : IItem
{
item.Features = _features.FindFor(typof(T));
}
}
I would call it a Failure to Encapsulate. It's a made up term, but it is real and seen quite often
A lot of people forget that encasulation is not just the hiding of data withing an object, it is also the hiding of behavior within that object, or more specifically, the hiding of how the behavior of an object is implemented.
By having an external DoSomething(), which is required for the correct program operation, you create a lot of issues. You cannot reasonably use inheritence in your list of things. If you change the signature of the "thing", in this case the string, the behavior doesn't follow. You need to modify this external class to add it's behaviour (invoking DoSomething() back to the derived thing.
I would offer the "improved" solution, which is to have a list of Thing objects, with a method that implements DoSomething(), which acts as a NOOP for the things that do nothing. This localizes the behavior of the thing within itself, and the maintenance of a special matching list becomes unnecessary.
If it were one string, I might call it a "magic string". In this case, I would consider "magic string array".
I don't know if there is a 'pattern' for writing code that is not maintainable or reusable. Why can't you just give them the reason?
In order to me the best is to explain that in term of computational complexity. Draw two chart showing the number of operation required in term of count(listOfThingsThatSupportX ) and count(listOfThings ) and compare with the solution you propose.
Instead of using interfaces, you could use attributes. They would probably describe that the object should be 'tagged' as this sort of object, even if tagging it as such doesn't introduce any additional functionality. I.e. an object being described as 'Thing A' doesn't mean that all 'Thing A's have a specific interface, it's just important that they are a 'Thing A'. That seems like the job of attributes more than interfaces.

How to use a specific interface on a C# object in IronPython

I have a C# class that implements 2 IEnumerable interfaces. How can I access either interface from IronPython?
My class:
public class MyClass : IEnumerable<TypeA>, IEnumerable<TypeB>
{
IEnumerator<TypeA> IEnumerable<TypeA>.GetEnumerator()
{
return _lstTypeA.GetEnumerator();
}
IEnumerator<TypeB> IEnumerable<TypeB>.GetEnumerator()
{
return _lstTypeB.GetEnumerator();
}
}
I tried the following in Python, but although it runs without errors it does not return any elements from the IEnumerable interface:
x = MyClass()
xA = clr.Convert(x, IEnumerable[TypeA])
for y in xA: print y
I don't like your class design. In particular that you implement two different versions of IEnumerable<T> that return different members. Two versions that return the same members is slightly better, but I still don't like that much.
Implementing IEnumerable so it's consistent with both IEnumerable<T>s isn't possible here. In particular that breaks the OfType and Cast linq methods.
You get overload resolution problems almost everywhere. Methods like Select<T>(this IEnumerable<T> ...) don't know which IEnumerable to take.
You can't use foreach on MyClass
If both TypeA and TypeB are reference types the variance of IEnumerable<out T> comes back to bite you. Since both of them offer IEnumerable<T'> for all their common ancestors.
It doesn't interact well with dynamically types languages
A class being a two different collections at the same time rarely makes sense. It usually indicates that something went wrong in the mapping from concepts to classes.
It's confusing and hard to understand. My intuition tells me it's evil and that I should burn it with fire :P
And Probably several more issues I didn't think of yet.
The work around is simple and clean: Have two separate enumerable properties.
public class MyClass
{
public IEnumerable<TypeA> TypeAs{get{_lstTypeA.Select(x=>x)}};
public IEnumerable<TypeB> TypeBs{get{_lstTypeB.Select(x=>x)}};
}
You need to call methods and properties as you were using reflection (that is actually what it happens under the hood).
In your case you should do:
x = MyClass()
enumerator = IEnumerable[TypeA].GetEnumerator(x)
then you can loop over enumerator:
for y in enumerator:
print y
how i use specified interface
clr.AddReference('Platform.CardHost')
from Platform import CardHost
from Platform.CardHost import ICardHost
host = CardHost.CardHost.CreateInstance('session')
# ICardHost is interface
# inside C#
# public interface ICardHost {
# IExtensionManager ExtensionManager { get; }
em = ICardHost.ExtensionManager.__get__(host)

C# has abstract classes and interfaces, should it also have "mixins"?

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();
}
}

What Advantages of Extension Methods have you found? [closed]

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! :)

Categories