Home > Back-end >  Do Foo.Do(int x) and FooExtensions.Do(this Foo foo, int x) have the same signature?
Do Foo.Do(int x) and FooExtensions.Do(this Foo foo, int x) have the same signature?

Time:07-14

I have a relatively decent understanding of method signature until I am faced with the following case.

Do both Foo.Do() and FooExtensions.Do() have the same signature?

class Foo
{
    public  void Do(int x)
    {
        Console.WriteLine("Foo.Do()");
    }
}

static class FooExtensions
{
    public static void Do(this Foo foo, int x)
    {
        Console.WriteLine("FooExtensions.Do()");
    }
}

Quoted from Methods (C# Programming Guide):

Methods are declared in a class, struct, or interface by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.

A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

CodePudding user response:

The "any method parameters" portion of the documentation you quoted means that they do not have the same signature: one has two parameters and the other doesn't. Not to mention they're declared on completely different classes, and one is static where the other is not.

It's true that the same syntax could be used when calling them (e.g. new Foo().Do(1)). However, in the case of the extension method, that's just syntax sugar: it could also be invoked explicitly as if it were a normal static method (FooExtensions.Do(new Foo(), 1)), whereas the instance method cannot.

Notably, if both methods exist, the rules of overload resolution will favor the method defined on the Foo class over the extension method, so you would be forced to invoke the static method explicitly.

  •  Tags:  
  • c#
  • Related