Extension methods resolve differently in Razor views than in pure C# code - by Uncreative username

Status : 

 


1
0
Sign in
to vote
ID 782032 Comments
Status Active Workarounds
Type Bug Repros 0
Opened 3/25/2013 7:11:53 AM
Access Restriction Public

Description

An extension method declared without a namespace for a class in another assembly will not take precedence over those in namespaces, even if it is a better match. This happens only within Razor views.
Sign in to post a comment.
Posted by Eilon [MSFT] on 7/30/2013 at 5:02 PM
Hi Uncreative,

This bug sure took a while to investigate and it turns out it's a somewhat obscure behavior of the C# compiler. Though the initial code was using Razor, that is only incidental to this behavior. I have reproduced this issue in a simple C# project. Depending on which "using" statement you use, you can switch whether the global namespace extension method will get called.

To work around this behavior, I have some suggestions:
1. Put the extension method in a namespace. This is generally a good practice to have. If you don't want to use your own namespace, you can put things in an existing namespace (though be aware of the issues that can cause in terms of other conflicts). If you own the extension methods, this is what I recommend.
2. Call the extension method as a static method. All extension methods are really just plain old static methods, but with the added bonus that they are also callable as extension methods. If you don't own the extension methods, this is what I recommend.

Here's the repro code in a simple C# console app:

//using SomeNamespace; // Use this namespace and you get both the "object" and the "integer" extension methods

namespace MyAppNamespace
{
    using SomeNamespace; // Use this namespace and you only get the "object" extension method

    class Program
    {
        static void Main(string[] args)
        {
            "abc".SomeExtension(5);
        }
    }
}

public static class MyGlobalExtensions
{
    public static void SomeExtension(this string s, int i)
    {
        System.Console.WriteLine("integer overload");
    }
}

namespace SomeNamespace
{
    public static class MyNamespacedExtensions
    {
        public static void SomeExtension(this string s, object o)
        {
            System.Console.WriteLine("object overload");
        }
    }
}

Thanks,
The ASP.NET Team
Posted by Macy [MSFT] on 3/25/2013 at 10:45 PM
Thanks for your feedback.

We are rerouting this issue to the appropriate group within the Visual Studio Product Team for triage and resolution. These specialized experts will follow-up with your issue.
Posted by Helen [MSFT] on 3/25/2013 at 7:52 AM
Thank you for your feedback, we are currently reviewing the issue you have submitted. If this issue is urgent, please contact support directly(http://support.microsoft.com)