views:

83

answers:

3

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

+7  A: 

You have to mark the interface as generic as well:

interface IHouse<T> where T : IRoom
{
    IEnumerable<T> Bedrooms { get; } 
}
Scott Dorman
IHouse<T> : where T :IRoom or IHouse<T> where T is right ?
anishmarokey
@anishmarokey: Yes, fixed the code.
Scott Dorman
+10  A: 

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.

Reed Copsey
Note, though, that without variance support this would prevent an implementing class from returning a `List<Room>` for some concrete `Room` type as the value of the property.
kvb
A: 

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.

Yuriy Faktorovich
Wondering why I was voted down. This statement is directly from MSDN.
Yuriy Faktorovich
+1 - and not just for agreeing with me ;) Generic constraints don't work on properties, for a reason.
Reed Copsey