I have an interface which uses a generic type extending another interface with the where
clause. Example:
public interface IEntityDataExtractor<T> where T : IEntity
{
public string[] ExtractRawStringData(T entity);
}
The IEntity
interface and a type extending this interface look like this:
public interface IEntity
{
int Id { get; set; }
}
public class Tender : IEntity
{
...
}
When i try to implement a concrete EntityDataExtractor for the Tender entity, i get the error that:
I do not understand why it is not accepted. I declare that the generic types used for the implementations should be of type IEntity some time down the hierarchy with the where
clause. Tender
implements, and therefore is an, IEntity
. Now i understand that i could solve this by simply having a completely unrestricted generic type T
, but the reason i am doing all this is because i need to store a list of the generic IEntityDataExtractor
interfaces, with the assigned ones being specific, because i want the type to be known within the specific implementation (e.g. TenderDataExtractor
) so i do not have to use forced casts or type conversion in the ExtractRawStringData
method. The result i need to achieve should look somewhat like this logic wise:
public class SomeClass
{
public List<IEntityDataExtractor<IEntity>> extractors { get; set; }
}
...Instantiating code
public void buildSomeClass()
{
List<IEntityDataExtractor<IEntity>> extractors = new();
extractors.Add(new TenderDataExtractor());
extractors.Add(new SomeOtherDataExtractor()); // etc.
SomeClass someClass = new();
someClass.extractors = extractors;
return someClass;
}
...Example of the tender data extractor
public class TenderDataExtractor : IEntityDataExtractor<Tender>
{
public string[] ExtractRawStringData(Tender entity)
{
// I can directly access members of Tender, not just IEntity,
// without having to do manual casts or type conversions here
}
}
The thing is, i cannot need to know the specific type at time of declaration (list in SomeClass for example), but will know it at time of assignment. For SomeClass it should just hand over any object of type IEntity to them, but the actual implementation called should know at compile them as shown above. The exact case is a bit different for the declaration part, but for brevity i made a simpler example. Is this not possible in C#?