tags:

views:

462

answers:

2

The question is this, why do I need to add an "import" directive on my Site.Master file to get Intellisense when the html helpers work without it.

Using a simple C# string extension method without a namespace == no problem. However, I wanted to put this extension in a namespace to be a good programmer.

If I wrap it in a namespace, you have to do a couple of things. Here is my extension:

namespace MySystemCore
{
    public static class StringExtensions
    {
        public static string F(this string s, params object[] args)
        {
            return string.Format(s, args);
        }
    }
}

So through trial and error, I have it working, but wanted to share my observations. Hopefully it may help someone else in the future.

NOTE: I am using the extension method in Site.Master

  1. Add "using MySystemCore;" to Site.Master.cs file (codebehind file)

    • Runtime error, no extension method found
  2. Add "<add namespace="MySystemCore">" to <namespaces> configuration block in web.config

    • Works, no intellisense
  3. Combine #1 and #2

    • Works, no intellisense
  4. Add "<%@ Import Namespace="MySystemCore" %>" to Site.Master file

    • Works, with intellisense
A: 

I agree that it is sometimes very annoying. But it is all with separation of concerns. You'll have to learn all your own and MS namespaces to find the correct extension methods.

JSC
+1  A: 

It's a VS limitation that when you add it to <namespaces> in web.config, IntelliSense doesn't show up.

But for the sake of completeness, I'll discuss the cause of it:

  • Method 1 is not a correct way to do it at all, since using directives (Imports will compile down to using by ASP.NET preprocessor) are scoped to a compilation unit (i.e. a single file)
  • Method 2 runs OK since it adds the using directive to the compilation options, which affects all compilation units in the application. If IntelliSense doesn't show up in this case, that's because VS is not smart enough to consider web.config.
  • Method 3 is effectively, just like 2. Method 1 is totally unrelated to the master file, it only affects .cs file as I mentioned before. Method 2 is like adding using to all .cs files automatically.
  • Method 4 works because VS understands that you're using it in the same file as it's working on.
  • Mehrdad Afshari