1

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

0

4 Answers 4

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
10

You have to mark the interface as generic as well:

interface IHouse<T> where T : IRoom
{
    IEnumerable<T> Bedrooms { get; } 
}

Comments

2

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;
}

Comments

1

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.

7 Comments

Wondering why I was voted down. This statement is directly from MSDN.
+1 - and not just for agreeing with me ;) Generic constraints don't work on properties, for a reason.
@ReedCopsey I would like to hear what that reason is, knowing that properties are resolved to methods anyway.
@Marco Generics don't work on the return types only - with generic methods, you need to specify the generic type as part of the method call. A generic property would require a new syntax for calling, which is odd, as a property is intended to look like a field for purposes of usage. Eliminating the availability of this keeps the language design cleaner, and doesn't have significant side effects, as you can always write generic methods. This about how you'd call this? Would you use: var rooms = house.Bedrooms<RoomType>; Syntax wouldn't be the same as anything else..
@ReedCopsey The point is that properties are translated to methods as such there is no technical aspect stopping properties of being generic. To be honest IMHO properties should not exist as they do, just get and set methods the java way, but that is other history.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.