why do extension functions ignore the where clause?


N

not_a_commie

I have here some example code (below) that I believe should work fine.
However, I get the error

Error 1 The call is ambiguous between the following methods or
properties:
'TestExtensions.ExtensionsOne.AddFive<TestExtensions.One>(TestExtensions.One)'
and
'TestExtensions.ExtensionsTwo.AddFive<TestExtensions.One>(TestExtensions.One)'
C:\workspace\TestProjects\TestExtensions\TestExtensions\Program.cs
44 4 TestExtensions

It's as though the resolution of the extension functions ignores the
where clause on the functions. As a workaround I can call the function
statically. I just think this should be resolvable.

namespace TestExtensions
{
public interface IOne
{
int Int { get; set; }
}

public class One: IOne
{
public int Int { get; set; }
}

public interface ITwo
{
int Int { get; set; }
}

public class Two : IOne
{
public int Int { get; set; }
}

public static class ExtensionsOne
{
public static void AddFive<T>(this T obj) where T : IOne
{
obj.Int += 5;
}
}

public static class ExtensionsTwo
{
public static void AddFive<T>(this T obj) where T : ITwo
{
obj.Int += 5;
}
}

class Program
{
static void Main(string[] args)
{
var one = new One();
one.AddFive();
}
}
}
 
Ad

Advertisements

N

not_a_commie

I should add that using classes instead of interfaces in the where
clause makes no improvement to the problem.
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

not_a_commie said:
I have here some example code (below) that I believe should work fine.

Why do you believe it should work? I can't see anything in the overload
resolution section of the spec (7.4.3.3 is the relevant bit here, I
believe) which suggests that generic constraints should make one
conversion better than another.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

interface 1
a question about binary serialization 3
XML to Dictionary using LINQ 2
synchronization demo 7
Overloading in generic interfaces 23
interface?! 5
Indexed class / list 45
Casting a derived class to base class 2

Top