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 proj
For anyone wondering, I had this same problem none of the answers worked. Turns out it was because the using
statement of the assembly was aliased:
using ex = MyApp.Example
Removing the alias worked, but I decided instead to add a duplicate, non-aliased using
, which also fixed the problem:
using MyApp.Example
using ex = MyApp.Example
For an example implementation that helped me:
(Note the this
keyword that has already been mentioned).
/// <summary>
/// Convert current bytes to string
/// </summary>
/// <param name="bytes">Current byte[]</param>
/// <returns>String version of current bytes</returns>
public static string StringValue(this byte[] currentBytes)
{
return string.Concat(Array.ConvertAll(bytes, b => b.ToString("X2")));
}
In my case, the Extension method was in an external reference which was referencing a different version of a component. I synchronized versions on both projects and it worked.
You should be careful about method signature
public static ILoggingBuilder AddCustomizedLogging(this ILoggingBuilder builder, string appInsightsKey)
"this" modifier is required for extension methods
For anyone who lands here while having the same problem in VB.NET, note that not only the extension method, but the module itself needs to be marked as Public
or else you'll get this error. This is the case at least with VS2015 Community and will likely be the case in other versions too.
In my case it said the reason the method was not recognized had nothing to do with extension methods, but an error in the same file which did not show up in the IDE - For me the solution was restarting the IDE and it suddenly displayed the actual error i had to fix.