Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overload static + Dynamic fails

Tags:

c#

overloading

I have come across this several times in the last week, and am curious to know the reason - I had a google, but couldn't find anything directly relevant.

I have a class with a dynamic method, and I can add a static method with the same interface:

public class MyClass
{
    public int MyMethod()
    {
        //do something #1;
    }

    public static int MyMethod()
    {
        //do something
    }
}

This is fine, but if I try to call the static method from the dynamic method, replacing #1 with return MyClass.MyMethod(), I get an error "The call is ambiguous between the following methods or properties: MyClass.MyMethod() and MyClass.MyMethod().
If the static method is deleted, the error changes to "An object reference is required..", which makes sense.

So why is this ambiguous? It has been prefaced with the class name to specify the static method, which works from anywhere else in code.
Why not here?

EDIT: I hadn't actually tried to compile it without the dynamic method calling the static one, I had just gone by VS not underlining it.
But still a similar question I suppose but with an added "Why can't there be both, as one is static, and one not"

like image 319
3Pi Avatar asked Nov 13 '22 22:11

3Pi


1 Answers

Besides here is a similar question on SO, giving some explanation, why you can't have two methods with the same signature.

public class MyClass
{
    public int MyMethod()
    {
        return 0;
    }

    public static int MyMethod() //Here compiler says, that you've already got method MyMethod with same parameter list
    {
        return 0;
    }
}

So, you can't have those methods at all

Have a look at this

At first:

The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.

Secondly:

Overloading of methods permits a class, struct, or interface to declare multiple methods with the same name, provided their signatures are unique within that class, struct, or interface.

EDIT

As for the reason why you get that error: you probably didn't compile yet and see an error underlined with red. If you do compile, you'll see the error underlined with blue not in the line where you call your static method, but on the line where the static method is defined.

like image 198
horgh Avatar answered Nov 15 '22 12:11

horgh