Dene
Dene

Reputation: 1581

Delegates/Anonymous Method in C# 2

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?

Upvotes: 1

Views: 590

Answers (4)

Tseng
Tseng

Reputation: 64150

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

Upvotes: 0

Grozz
Grozz

Reputation: 8425

Action reusableFunc = () => Console.WriteLine("Hello, world!");

somewhere:

reusableFunc();

elsewhere:

reusableFunc();

Upvotes: 0

Matt Ellen
Matt Ellen

Reputation: 11592

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.

Upvotes: 0

Kirk Woll
Kirk Woll

Reputation: 77546

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.

Upvotes: 3

Related Questions