John Smith
John Smith

Reputation: 3

C# Compiler Error when name of auto-property and a method is identical within interface definition

I'd like to specify an interface as follows:

public interface MyInterface
{
  int MyMember
  {
    get;
  }

  int MyMember(string parameter);
}

But that leads to a compiler error:

Error CS0102 The type 'MyInterface' already contains a definition for 'MyMember' MyComponent.Interfaces

So my question is why is this a problem for the compiler.

Upvotes: 0

Views: 58

Answers (1)

René Vogt
René Vogt

Reputation: 43916

Because the names are equal. The compiler cannot decide which of the two symbols you are referring to.

Note that you can assign the method MyMember to a delegate variable:

Func<string, int> method = instance.MyMember;

Here the compiler could actually know that you mean the method since the property has another signature, but what about that:

var somethign = instance.MyMember;

There are two many problems when you allow equal names in the same scope. And it's pretty sure that the developer who tries to do this will confuse himself and his co-workers leading to more errors.

So if I had to develop a programming language, I would not allow this.

Upvotes: 4

Related Questions