Using limited general extension methods in a separate assembly gives a reference error

I created a separate assembly to contain common extension methods, extension methods use classes from System.Web.dll(and others).

When I create a new project (Console Application) that references an assembly Utilities.dllthat contains extension methods, I don’t need to add a reference to System.Web.dllthe new project if it doesn’t use extension methods that extend any class in the assembly System.Web.dll(for example, System.Web.UI.Control).

When one of the extension methods is a universal method, everything will work as expected. But as soon as I add a restriction on the general method that restricts it to a class in the assembly System.Web.dll, the compiler will complain that my new project (Console application) needs a link to System.Web.dll, even if the new project is still not using anything in this assembly.

In other words, as long as I don't have restrictions on my common methods, everything compiles, but as soon as I add the restriction, the compiler complains.

An example of my extension methods (compiled as a library Utilities.dll):

public static class StringExtensions
{
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }
}

public static class ControlExtensions
{
    // If I remove the where clause it compiles
    public static T FildChild<T>(this Control parent, string id)
        where T : Control
    {
        throw new NotImplementedException();
    }
}

And here is a new console application that will not compile (unless I also add a link to System.Web.dll):

    static void Main(string[] args)
    {
        bool isEmpty = "Hello World!".IsNullOrEmpty();

        Console.ReadLine();
    }


<B> Update: As Mark (below) noted, using the insult method in a separate namespace resolves the issue.

But the question remains why the problem is the problem, while the Control type was already used as a parameter for the method. and why the namespace is the solution when I already use the directive at the top.

+5
source share
2 answers

well yes! To compile, it must be able to resolve everything in a public / secure API. Otherwise, it cannot provide a restriction. I assume that it must recognize types in order to find out if the extension method is a candidate for the method.

, "Web", , . , . , , .

, , , API. .

+5

@Marc . , , -, , , Com.Company.Extensions.Web Com.Company.Extensions. -, -- .

+1

All Articles