Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly use extension method

I'm having a List<T> and want get the values back in reverse order. What I don't want is to reverse the list itself.

This seems like no problem at all since there's a Reverse() extension method for IEnumerable<T> which does exactly what I want.

My problem is, that there's also a Reverse() method for List<T> which reverses the list itself and returns void.

I know there are plenty of ways to traverse the list in reverse order but my question is:

How do I tell the compiler that I want to use the extension method with the same name?

var list = new List<int>(new [] {1, 2, 3});
DumpList(list.Reverse());                   // error
like image 931
VVS Avatar asked Jun 12 '09 16:06

VVS


People also ask

What is the use of extension methods?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is the difference between a static method and an extension method?

The only difference between a regular static method and an extension method is that the first parameter of the extension method specifies the type that it is going to operator on, preceded by the this keyword.

Why extension methods are static?

Essentially, an extension method is a special type of a static method and enable you to add functionality to an existing type even if you don't have access to the source code of the type. An extension method is just like another static method but has the “this” reference as its first parameter.


2 Answers

The best way to explictly bind to a particular extension method is to call it using shared method syntax. In your case, you would do that like:

DumpList(Enumerable.Reverse(list));

The problem with some of the other approaches mentioned here is that they won't always do what you want. For example, casting the list like so:

((IEnumerable)list).Reverse()

could end up calling a completely different method depending on the namespaces you have imported, or what type the calling code is defined in.

The only way to be 100% sure you bind to a particular extension method is to use the shared method syntax.

like image 157
Scott Wisniewski Avatar answered Oct 11 '22 19:10

Scott Wisniewski


var list = new List<int>(new [] {1, 2, 3});
DumpList((list as IEnumerable<int>).Reverse());

OR

IEnumerable<int> list = new List<int>(new [] {1, 2, 3});
DumpList(list.Reverse());
like image 40
John Fisher Avatar answered Oct 11 '22 20:10

John Fisher