user1025901
user1025901

Reputation: 1909

Why we need an explicit conversion incase od Extension method and not for static methods?

Why Extension methods do not use implicit conversions but static methods do? Can anybody explain with a proper example?

Thanks

Upvotes: 0

Views: 74

Answers (1)

Chris Shain
Chris Shain

Reputation: 51319

Because the C# spec states:

An extension method Ci.Mj is eligible if:

· Ci is a non-generic, non-nested class

· The name of Mj is identifier

· Mj is accessible and applicable when applied to the arguments as a static method as shown above

· An implicit identity, reference or boxing conversion exists from expr to the type of the first parameter of Mj.

As far as the C# spec is concerned, a user-defined conversion operator is different than an implicit reference conversion, and certainly different than an identity or boxing conversion.

For a hint on why:

public static class Extensions
{
    public static void DoSomething(this Bar b)
    {
        Console.Out.WriteLine("Some bar");
    }

    public static void DoSomething(this Boo b)
    {
        Console.Out.WriteLine("Some boo");
    }
}

public class Foo
{
    public static implicit operator Bar(Foo f)
    {
        return new Bar();
    }
    public static implicit operator Boo(Foo f)
    {
        return new Boo();
    }
}

public class Bar { }
public class Boo { }

public class Application
{
    private Foo f;
    public void DoWork()
    {
        // What would you expect to happen here?
        f.DoSomething();

        // Incidentally, this doesn't compile either:
        Extensions.DoSomething(f);
    }
}

C# could not unambiguously choose which implicit conversion to execute.

Upvotes: 1

Related Questions