Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Methods not Recognized

What is necessary to have an extension method honored when it exists in an imported assembly? I built one in a class library project but it is not recognized in my web project which references the library. All the other classes and methods in the library are honored and visible but this extension method is not. The extension method is visible when used within the library.

like image 219
ChiliYago Avatar asked Apr 07 '10 16:04

ChiliYago


People also ask

What are the extension methods in C#?

In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.

Can we add extension method in interface?

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself.

Can you add extension methods to an existing static class?

No. Extension methods require an instance of an object.

What is the correct definition of extension methods?

Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.


2 Answers

Referencing an assembly containing a class with extension methods is not enough. You need to import the namespace containing the class in each of your source file where you want to use the extension methods.

For example, to use LINQ-to-objects, you need to reference the System.Core assembly and import the System.Linq namespace (which contains the Enumerable class with the LINQ extension methods):

using System.Linq; 
like image 166
dtb Avatar answered Sep 24 '22 05:09

dtb


If the Extension method is callable when not using the Extension syntax, use the Format:

this.MyExtensionMethod() 

That cleared up my problem of not finding the Extension method of a class in VS2010.

like image 30
Wolfgang Grinfeld Avatar answered Sep 24 '22 05:09

Wolfgang Grinfeld