Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

why do extension functions ignore the where clause?

10 views
Skip to first unread message

not_a_commie

unread,
Apr 4, 2008, 11:09:02 AM4/4/08
to
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();
}
}
}

not_a_commie

unread,
Apr 4, 2008, 11:12:47 AM4/4/08
to
I should add that using classes instead of interfaces in the where
clause makes no improvement to the problem.

Jon Skeet [C# MVP]

unread,
Apr 4, 2008, 11:20:54 AM4/4/08
to
not_a_commie <notac...@gmail.com> wrote:
> 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.

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

0 new messages