copygirl
copygirl

Reputation: 61

c# Multiple generic constraints on return type (similar to Java)

I'd like to write code similar to this:

public IEnumerable<TSystem> GetSystems<T>() where TSystem : T
{
    _systems.Where(system => system is T).Cast<TSystem>();
}

But I'm getting the error 'GetSystems<T>()': A constraint references nonexistent type parameter 'TSystem' (CS0699).

I think something similar would be possible in java using &:

public IEnumerable<System & T> GetSystems<T>() { ... }

If I include the generic constraint in the type parameters of the method, I would have to specify a specific type which implements T instead of working for all types which implement it.

As for why, it would be nice to be able to treat the returned IEnumerable as both an IEnumerable<System> as well as IEnumerable<T> without casting.

GetSystems<ISomeInterface>().SomeSystemExtensionMethod(
    system => system.SomeInterfaceMethod());

public static void SomeSystemExtenstionMethod(
    this IEnumerable<System>, Action<System> action) { ... }

Is this possible in C#?

Upvotes: 1

Views: 130

Answers (1)

bashmohandes
bashmohandes

Reputation: 2376

Use this declaration instead

public IEnumerable<TSystem> GetSystems<T, TSystem>() where TSystem : T

In C# all the generic type parameters for either input or output types must be included in between < .. >

Upvotes: 1

Related Questions