This is a question about Extension Method visibility in .Net (specifically C#), and why intellisense may work, but the compiler fail on the same piece of code.
Picture this...
I have .Net 3.5 class library consisting of a bunch of objects and a single Extension Methods class. Here is one of the methods:
namespace MyApp.Extensions
{
public static class ExtensionMethods
{
public static string ToTitleCase(this string Origcase)
{ string TitleCase = Origcase;
... implementation ...
return TitleCase;
}
}
To use the extension methods within the class library itself, each class that requires one of the methods needs to specify:
using MyApp.Extensions;
Since that is a different namespace than the rest of the library. All of that works fine.
Now, a .Net 2.0 web site properly references this library, and a class file wishes to use the library. So it declares that it is:
using MyApp.Extensions
That SEEMS to work just fine, and when typing a string, Intellisense does see the extension method dangling off a string instance:
http://www.flipscript.com/test/ToTitleCase.jpg
I love it when a plan comes together!
However, that's the end of the joy.
When attempting to Build the web site, the build fails with the following message:
http://www.flipscript.com/test/titlecaseerror.jpg
When attempting to directly copy the ExtensionMethods class into the web project, the build again fails. This time, because the word "this" was not expected.
Oddly enough, the extension method does work as a normal static method:
http://www.flipscript.com/test/titlecaseok.jpg
...and the Build works just fine (so the problem is NOT actually with the "this" keyword). In fact, the build works whether the ExtensionMethods class is in the class library or the web site.
In other words, this does solve the problem, and the build will succeed.
...but the solution sucks.
Question: Is there some sort of secret trick to get Extension Methods to work correctly in this scenario?
http://www.flipscript.com/test/ToTitleCase.jpg
I've tried the "namespace System.Runtime.CompilerServices" trick, but that didn't seem to help.
What would cause Intellisense to see an extension method correctly, and the compiler to fail?
Note: The contrived example variable should have been called 'name' instead of 'FirstName', but you get the idea.