3

I was thinking of List's functionality and not thinking about the fact that Count() was an extension method when I made the false assumption that I could write a class having a same named property and method. The motivation in my mind at the time was I could "parameterize a property" for special cases.

I realize now that I can do it, provided I utilize an extension method.

Is this intentionally disallowed in classes but allowed in extensions or simply a non-existant feature?

void Main()
{
    var list = new List<string>();

    // You compile code that gets the property named Count
    // and calls the method named Count()
    list.Add("x");
    Console.WriteLine (list.Count);
    list.Add("x");
    Console.WriteLine (list.Count());

    var c = new C();
    Console.WriteLine (c.Count);
    Console.WriteLine (c.Count());
}

public class C
{
    public int Count { get { return 3; } }

    // But you cannot compile a class that contains both a property
    // named Count and a method named Count()
    //public int Count () { return 0; } // <-- does not compile
}

public static class X 
{
    public static int Count(this C c)
    {
        return 4;
    }
}
Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121
  • 1
    See the answer for the first part of your question here: http://stackoverflow.com/questions/1293201/calling-constructor-overload-when-both-overload-have-same-signature and here: http://stackoverflow.com/questions/1667808/why-does-the-compiler-find-this-ambiguous. The answer for the second part was given by Tigran already. – Dennis May 23 '12 at 18:39

2 Answers2

3

I remember asking this question like 10 years ago on one of Microsoft groups:

http://www.developmentnow.com/g/36_2003_9_0_0_195928/methods-and-properties-of-the-same-name.htm

and as you can see there was no convincing answer.

This is of course easily possible in CIL, as properties translate to paris of getXX/setXX methods.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
1

This is because Count(this C c) is an extension method and doesn't actually make a part of the type.

That means that you can have a method Count() in C + extension Count(). If you call it, will be called instance method.

So if we think about a property there is even less problems with that.

Tigran
  • 61,654
  • 8
  • 86
  • 123