Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a generically constrained property on an interface?

Tags:

c#

generics

This is perfectly valid:

public interface IWidgetGetter
{
    IEnumerable<T> GetWidgets<T>() where T : IWidget;
}

That is, it defines an untyped interface that includes a method to get a IEnumerable of some type that implements IWidget.

How do I make this into a property?

Things that don't work:

IEnumerable<T> Widgets<T> { get; set; } where T : IWidget
IEnumerable<T> Widgets { get; set; } where T : IWidget
IEnumerable<T> Widgets where T : IWidget { get; set; }
IEnumerable<T> Widgets<T> where T : IWidget { get; set; }
like image 964
Dave Mateer Avatar asked Dec 19 '22 08:12

Dave Mateer


1 Answers

There is no such thing as a generic property.

A type parameter is still a kind of parameter. Just like you couldn't turn a method that takes an argument into a property, you can't turn a generic method into a property either.

The closest thing you could do is this:

public interface IWidgetGetter<T> where T : IWidget
{
    IEnumerable<T> Widgets { get; }
}
like image 85
Lucas Trzesniewski Avatar answered Mar 08 '23 23:03

Lucas Trzesniewski