Is there a definite reason that properties and methods with the same name are forbidden in classes, but allowed as extension methods?

I was thinking about List functions and not thinking that Count () was an extension method when I made the false assumption that I could write a class with the same property name and method name. The motivation in my mind at that time was that I could “parameterize a property” for special cases.

Now I understand that I can do this if I use the extension method.

Is this intentionally forbidden in classes, but allowed in extensions or just a non-existent function?

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;
    }
}
+3
source share
2 answers

, Count(this C c) .

, Count() C + extension Count(). , .

, , .

+1

All Articles