views:

66

answers:

5

Possible Duplicate:
What are Extension Methods?

Hi,
After googlin got to know a bit about Extension methods but not very clear why we need to use extension methods and how does it work?

Please suggest.

Thanks,
Subhen

A: 

Extension methods can be useful if you need to add functionality to a third party .dll or some component which you do not have direct access to the source code.

So for example, you don't have direct access to modify the String class but with extension methods you can add methods to it. ( or give that impression to the user of the class)

Ben Cawley
No, this is not true.
this. __curious_geek
Yes it is true. I say it 'can' be useful to add functionality to a third party component that you don't have source code access... True or not?
Ben Cawley
@Ben: Absolutely False. You can never change anything in the type, you can only play with instances and that's what extension methods do. They just play with the instance not the type.
this. __curious_geek
+1  A: 

Extension methods allow you to add methods to existing types without having to create derived classes. It's also useful when you haven't got access to the code such as the framework. More info here

JLWarlow
No, this is not true.
this. __curious_geek
Yes it is true.
Ben Cawley
@ this. __curious_geek Can you expand on that?
JLWarlow
When did this became true ? Extension methods are just syntactic sugars and nothing else. please read my answer.
this. __curious_geek
@JLWarlow: Yes, please read my answer.
this. __curious_geek
Nobody claimed that extension methods gives you access to private methods. But they enable you to expand (at least sort of) any class even if you do not have its source code.
codymanix
@codymanix: define `expand`.
this. __curious_geek
A: 

What is an extension method ?

Refer to this question - http://stackoverflow.com/questions/403539/what-are-extension-methods

Why do we need to use it ?

Somehow, I don't agree to the idea of using extension methods to extend an existing type since practically this is impossible. The only reason why you want to use extension method is to bring fluency and readabilty on any type.

Check this code..

string str = "Hello world";
string result = Helper.Method2(Helper.Method1(str));

This code with extension methods can be written as below.

string str = "Hello world";
string result = str.Method1().Method2();
//compiler ultimately compiles this code as Helper.Method2(Helper.Method1(str));

which one is more fluent and readable ? The one with the extension methods.

this. __curious_geek
A: 

An extension method is simply something that adds a little "syntactic sugar", making it easier to write code.

For example, there are lots of extension methods on the IEnumerable<T> interface. Some of them are defined in a static class called EnumerableExtensions, maybe like this:

public static class EnumerableExtensions
{
    public static IEnumerable<T> Where<T>(this IEnumerable<T> items, Expression<Func<T, bool>> predicate)
    {
        // Filter based on the predicate and return the matching elements
    }
}

Notice that both the class and the method are marked static, and that there is a this keyword infront of the first parameter. this marks this method as an extension method.

Now, to use this method on an instance of IEnumerable<T>, say myTees, you just type

var filtered = myTees.Where(t => t.IsCool);

But this is not the code that is actually compiled into the .dll. The compiler replaces this call to the extension method, with a call to

var filtered = EnumerableExtensions.Where(myTees, t => t.IsCool);

which, as you see, is just a regular static method on another class.

So, one main point of extension methods is to make the usage of static methods a little smoother, producing more readable code.

Of course, this also gives the effect that you can extend any type in the .NET framework - even (and especially) types you haven't created yourself! It's as simple as writing a regular static method that takes the type you want to extend as a first parameter, prefix it with this and mark the containing class static. Apple pie is served! =)

Tomas Lycken
A: 

They allow you, to extend allready existing Classes with new Methods. without changing their code, or Dll.

the benefit is, they are intentional to use.

for example: say you often need in your project to cut strings until a specific string is found.

normally you write code like this:

input.Substring(0,input.LastIndexOf(tofind))

this has the problem, that if the string is not found, you get an exception. and developers are lazy. so if they think, this will not happen, they just do not catch it or refactor all occourances. so, you could make an method somewhere.

public static class StringExtensions
        {

            public static string SubstringTill(string input, string till, StringComparison comparisonType = StringComparison.CurrentCulture)
            {
                int occourance = input.LastIndexOf(till, comparisonType);

                if (occourance < 0)
                    return input;

                return input.Substring(0, occourance);
            }
        }

and... then the hard part. send an email out to all developers, that this now exists, and that they should use it in the future. and also put it into the documentation for new developers... or:

just add a "this" in the method like

public static string SubstringTill(this string input, string till, StringComparison comparisonType = StringComparison.CurrentCulture)

and you get an extension method. and when anybody writes code, and needs such a code, he sees that uh, there is allready a method done by someone that does this. so reusability and DRY is easier to achieve. if its properly documented what it does, and what exceptions can occour.

cRichter