views:

27

answers:

3

I have two methods that are identical. one is

    public void ExtendFrameIntoClientArea(Window w, int amount)
    {
        if (internals.DwmIsCompositionEnabled())
        {
            WindowInteropHelper wi = new WindowInteropHelper(w);
            internals.DwmExtendFrameIntoClientArea(wi.Handle, new internals.MARGINS(amount));
        }
    }

and the other is

public void ExtendFrameIntoClientArea(this Window w,int amount)
        {
            this.ExtendFrameIntoClientArea(w, amount);
        }

One of them is an extension method and the other one is not. This however, results in an error "This call is ambiguous"

How would I work around this?

+3  A: 

Extension methods should be static.

public static class XExtender
{
    public static void A(this X x)
    {
        x.A(x);
    }
}
public class X
{
    public void A(X x)
    {

    }
}

Extension methods should have a static class and a static method.

BrunoLM
I believe this is just a typo - won't compile without the static modifier.
Daniel Brückner
I just wonder: An extension method will never be called if it has the same signature as a method defined in the type: http://bit.ly/91A9Jn (General Guidelines), so whats the point?
Nick Martyshchenko
A: 

According to C# Version 3.0 Specification, the search order is:

  • instance method in the type definition
  • extension method in the current namespace
  • extension method in the current namespace’s parents namespaces
  • extension method in the other namespaces imported by “using”

So how you declared your methods and where?

Nick Martyshchenko
A: 

I think the error is not caused by the extension method.

First, an extension method

public static void ExtendFrameIntoClientArea(this Window w, int amount) { }

(by the way, you missed the static modifier) would be ambiguous with a instance method

public void ExtendFrameIntoClientArea(int amount) { }

declared in the class Window but not with a instance method

public void ExtendFrameIntoClientArea(Window w, int amount) { }

no matter in what class it is declared. Further - as far as I remember - instance methods take precedence over extension method - so they should never be ambiguous with extension methods. I suggest to have a look at the error message again and verify that you are looking at the right methods.

Daniel Brückner