Why does C# not allow generic properties?

22,210

Solution 1

Technically, the CLR supports only generic types and methods, not properties, so the question is why it wasn’t added to the CLR. The answer to that is probably simply “it wasn’t deemed to bring enough benefit to be worth the costs”.

But more fundamentally, it was deemed to bring no benefit because it doesn’t make sense semantically to have a property parameterised by a type. A Car class might have a Weight property, but it makes no sense to have a Weight<Fruit> and a Weight<Giraffe> property.

Solution 2

This Generic Properties blog post from Julian Bucknall is a pretty good explanation. Essentially it's a heap allocation problem.

Solution 3

My guess is that it has some nasty corner cases that make the grammar ambiguous. Off-hand, this seems like it might be tricky:

foo.Bar<Baz>=3;

Should that be parsed as:

foo.Bar<Baz> = 3;

Or:

foo.Bar < Baz >= 3;
Share:
22,210
Sunny Milenov
Author by

Sunny Milenov

Updated on April 09, 2021

Comments

  • Sunny Milenov
    Sunny Milenov about 3 years

    I was wondering why I can not have generic property in non-generic class the way I can have generic methods. I.e.:

    public interface TestClass
    {
       IEnumerable<T> GetAllBy<T>(); //this works
    
       IEnumerable<T> All<T> { get; } //this does not work
    }
    

    I read @Jon Skeet's answer, but it's just a statement, which most probably is somewhere in the specifications.

    My question is why actually it is that way? Was kind of problems were avoided with this limitation?