Reputation: 4985
I'm writing an interface and I want to declare a property that returns a generic collection. The elements of the collection should implement an interface. Is this possible and, if so, what is the syntax.
This doesn't compile, what's the right way to do this?
interface IHouse
{
IEnumerable<T> Bedrooms { get; } where T : IRoom
}
Thanks
Upvotes: 1
Views: 2871
Reputation: 45
There are no good reasons why Microsoft chose to add this restriction. Under the hood properties are just a pair of methods, and generic methods are already supported.
I have hit this restriction a couple of times, and had to resort to adding explicit get and set methods instead:
interface IHouse
{
IEnumerable<T> GetBedrooms<T>() where T : IRoom;
}
Upvotes: 2
Reputation: 42516
You have to mark the interface as generic as well:
interface IHouse<T> where T : IRoom
{
IEnumerable<T> Bedrooms { get; }
}
Upvotes: 10
Reputation: 68667
Generic is for classes and methods, not properties. If a class/interface is generic, then you can use the type in the property. I agree with Reed's solution.
Upvotes: 1
Reputation: 564383
Why use generics? Just do:
interface IHouse
{
IEnumerable<IRoom> Bedrooms { get; }
}
This is cleaner, and since you're already restricting to the interface, it will act nearly identically.
Upvotes: 12