2

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

Community
  • 1
  • 1
Simsons
  • 11,081
  • 36
  • 131
  • 242
  • 2
    Exact dup : http://stackoverflow.com/questions/403539/what-are-extension-methods – Krunal Jul 21 '10 at 09:10
  • 1
    You can also check http://stackoverflow.com/questions/487904/what-advantages-of-extension-methods-have-you-found – Krunal Jul 21 '10 at 09:15

5 Answers5

1

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

John Warlow
  • 2,860
  • 1
  • 29
  • 45
1

What is an extension method ?

Refer to this question - 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.

Community
  • 1
  • 1
this. __curious_geek
  • 40,897
  • 20
  • 108
  • 134
0

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
  • 1,516
  • 15
  • 28
  • 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 Jul 21 '10 at 09:24
  • 1
    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 Jul 21 '10 at 09:28
0

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 Aschan
  • 53,075
  • 51
  • 214
  • 362
0

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
  • 1,383
  • 6
  • 7