Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# extension methods in a "site.master" template thats wrapped in a namespace quandary

Tags:

c#

asp.net

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
like image 783
mikekidder Avatar asked Nov 18 '25 21:11

mikekidder


1 Answers

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.
  • like image 122
    mmx Avatar answered Nov 20 '25 10:11

    mmx



    Donate For Us

    If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!