C# pass generic type as a generic type parameter?

96 views Asked by At
public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T>
{
    return list.Skip (count).Concat(list.Take(count));
}

I want to achive something like this, where T is a type paramter to IEnumerable, and C implements IEnumerable. This is the syntax I came up with but it does not pass the compiler. Any way to get what I want? Thanks!

1

There are 1 answers

2
MakePeaceGreatAgain On BEST ANSWER

Why don´t you leave out the C-param at all?

public static IEnumerable<T> RotateLeft<T>(IEnumerable<T> list, int count)
{
    return list.Skip (count).Concat(list.Take(count));
}

EDIT: As Suresh Kumar Veluswamy already mentioned you may also simply cast your result to an instance of C:

public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T>
{
    return (C) list.Skip(count).Concat(list.Take(count));
}

However whilst this will solve your compiler-issue it won´t let you get what you want as it returns an InvalidCastException when trying to cast the result of Concat to an instance of C.