Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can there be ambiguity between a property getter and a method with one argument?

I can't believe I've never come across this before, but why am I getting a compiler error for this code?

public class Main
{
    public Main()
    {
        var ambiguous = new FooBar(1);
        var isConfused = ambiguous.IsValid; // this call is ambiguous
    }
}

public class FooBar
{
    public int DefaultId { get; set; }

    public FooBar(int defaultId)
    {
        DefaultId = defaultId;
    }

    public bool IsValid
    {
        get { return DefaultId == 0; }
    }

    public bool IsValid(int id)
    {
        return (id == 0);
    }
}

Here is the error message:

Ambiguity between 'FooBar.IsValid' and 'FooBar.IsValid(int)'

Why is this ambiguous?

I'm thinking there are two reasons it should not be ambiguous:

  1. There are no parenthases after IsConfused.
  2. There is no int argument for IsConfused.

Where is the ambiguity?

like image 795
devuxer Avatar asked Jul 07 '11 19:07

devuxer


1 Answers

There error is because it is ambiguous since it's declared using var. It could be:

bool isConfused = ambiguous.IsValid;

Or:

Func<int, bool> isConfused = ambiguous.IsValid;

Using var requires the compiler to be able to infer the exact meaning, and in this case, there are two possibilities.

However, if you remove the var, you'll still get a (different) error, since you can't have two members with the same name, one a property, and one a method.

like image 76
Reed Copsey Avatar answered Oct 27 '22 11:10

Reed Copsey