Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about ambiguous calls in C#

I have a question that's not really a problem, but something that made me a little curious.

I have a class with two methods in it. One is a static method and the other one is an instance method. The methods have the same name.

public class BlockHeader
{
    public static BlockHeader Peek(BinaryReader reader)
    {
        // Create a block header and peek at it.           
        BlockHeader blockHeader = new BlockHeader();
        blockHeader.Peek(reader);
        return blockHeader;
    }

    public virtual void Peek(BinaryReader reader)
    {
        // Do magic.
    }
}

When I try to build my project I get an error saying:

The call is ambiguous between the following methods or properties: 'MyApp.BlockHeader.Peek(System.IO.BinaryReader)' and 'MyApp.BlockHeader.Peek(System.IO.BinaryReader)'

I know that the method signatures are virtually the same, but I can't see how I possibly could call a static method directly from an instance member.

I assume that there is a very good reason for this, but does anyone know what that reason is?

like image 547
Patrik Svensson Avatar asked May 20 '09 09:05

Patrik Svensson


2 Answers

The general policy of the C# design is to force you to specify wherever there is potential ambiguity. In the face of refactoring tools that allow one to rejig whether things are static or not at the drop of a hat, this stance is great - especially for cases like this. You'll see many other cases like this (override vs virtual, new for shadowing etc.).

In general, removing this type of room for confusion will make the code clearer and forces you to keep your house in order.

EDIT: A good post from Eric Lippert discusses another reason for this ambiguity leading to the error you saw

like image 82
Ruben Bartelink Avatar answered Sep 21 '22 01:09

Ruben Bartelink


Here's a excerpt from the C# 3.0 language specification.

The signature of a method must be unique in the class in which the method is declared. The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. The signature of a method does not include the return type.

The 'static' modifier is not part of the signature so your example violates this rule of unique signatures.

I don't know the reason behind the rule, though.

like image 28
Vizu Avatar answered Sep 21 '22 01:09

Vizu