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

流过昼夜 提交于 2019-12-01 15:21:38

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.

It's confusing you would get that particular message, but it is not legal to have two members with the same name (excepting method overloading). Here your property and method have the same name. This is the same reason you can't have a property and an inner class with the same name. Fields, properties, methods, and inner classes are all members of the enclosing type and must have unique names.

You would get an error that "FooBar already contains a definition for IsValid"

At first, it might seem that the compiler could always figure out whether you're calling the method or using the property -- after all, the method has parentheses after it, and the property doesn't.

That doesn't hold up, though. You can use a method without the parentheses:

void Foo() { ... }
void Bar(Action action) { ... }

Bar(Foo);

And you can use a property with parentheses:

Action MyProperty { get; set; }

MyProperty();

The only way to make sure there's no ambiguity is to disallow having a method and a property with the same name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!