Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a specific reason same-named properties and methods are disallowed in classes but allowed as extension methods?

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;
    }
}
like image 384
Aaron Anodide Avatar asked Jan 29 '26 12:01

Aaron Anodide


2 Answers

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.

like image 182
Wiktor Zychla Avatar answered Jan 31 '26 02:01

Wiktor Zychla


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.

like image 22
Tigran Avatar answered Jan 31 '26 00:01

Tigran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!