I just looked at this posting: What is the best or most interesting use of Extension Methods you’ve seen?
I've never heard of extension methods. Do they apply to every language?
What is the point of them? In that particular posting I did not understand the example.
An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.
An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
The only advantage of extension methods is code readability. That's it. Extension methods allow you to do this: foo.
No, they do not apply to every language. They are a language-specific feature, offered by C# and Visual Basic (other languages may have adopted them since, I don't know).
The point of them is to provide a convenient syntax for calling utility methods on a class or interface. In C# 2, a utility method would be called through a static class, passing the argument in the normal way:
IEnumerable<string> someStrings;
int count = EnumerableHelpers.Count(someStrings);
With extension methods, this can be written more conveniently using something that looks like normal member method syntax:
int count = someStrings.Count();
even though Count() is not a member of the IEnumerable<string>
interface. So extension methods let you appear to add members to classes or interfaces that you don't control.
They are available to C# and VB. They allow you to simulate the addition of methods to classes that are not under your control.
You could, for instance, you could add a WordCount
method to string.
So instead of
MyStringUtils.WordCount( "some string" )
You could just write "some string".WordCount()
.
public static class MyExtensions
{
public static int WordCount(this String str)
{
return MyStringUtils.WordCount( str );
}
}
This is strictly "syntactic sugar" and aids in readability. You're essentially creating a static method that will be shown in the IntelliSense for the target type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With