views:

59

answers:

4

In C# 1. You don't have delegate sorting or comparison options. You might be forced to do it by creating another type which implements IComparer to sort your collections in ArrayList. But starting from c# 2. You can use delegates for your comparisons. Look the following example.

List<Product> products = Product.GetSampleProducts();
products.sort(delegate(Product p1, Product p2) {return p1.Name.CompareTo(p2.Name);});

I can see
1) how the delegate (Anonymous Method) makes life easy
2) how the code becomes readable and how it helped me do the Comparison with out creating another type.

My question is - What if we want to use this comparison in Multiple areas in my application? don't you think this will force me to write the same "Anonymous Method" again and again? Don't you think this is against the OOP of re-usability?

+3  A: 

If you're using the same anonymous method over and over, it should probably be a static method somewhere. Then you just pass a reference to that instead of the delegate. Anonymous delegates should be for one-offs, perhaps because it needs a reference to closure variables/parameters.

Kirk Woll
A: 

If you reuse a piece of code frequently, refactor it into its own method.

As you suggest, repeating a chunk of code does go against reusability. I can't think of a pattern that would make you do that.

Matt Ellen
A: 
Action reusableFunc = () => Console.WriteLine("Hello, world!");

somewhere:

reusableFunc();

elsewhere:

reusableFunc();
Grozz
A: 

Something in between should do it

delegate void MyDelegate(Product p1, Product p2);

MyDelegate myDelegate = delegate(Product p1, Product p2e) { 
    return p1.Name.CompareTo(p2.Name);
};

products.sort(myDelegate);
products2.sort(myDelegate);
Tseng