just-a-hriday
just-a-hriday

Reputation: 149

Generic type where T is derived from a generic type

I have an abstract class called Foo, which is generic.
And there's a class called Bar, which is also generic, but needs T to be derived from Foo. But I can't do that without specifying a generic type for Foo, which I don't want to do - I want any class derived from Foo to be eligible.

abstract class Foo<T> { }

class Bar<T> where T : Foo { }
// This gives me CS0305 - Using the generic type Foo<T> requires 1 type argument.

I'm sure there's some sort of super obvious solution I'm missing.

Upvotes: 3

Views: 1465

Answers (3)

Zolt&#225;n Balogh
Zolt&#225;n Balogh

Reputation: 185

You can do this by creating a class that is not generic like the following

public abstract class Foo { }
public abstract class Foo<T> : Foo { }

And now you can use your constrain with Foo

public class Bar<T> where T : Foo { }

And this will be required to T be a type of Foo and as long as you derive generic Foo<> from non-generic Foo your T must be Foo<T>

Example of usage:

public abstract class Foo { }
public abstract class Foo<T> : Foo { }
public abstract class Boo : Foo<string> { }

public class Bar<T> where T : Foo { }

public class BarTest : Bar<Boo> { }

Upvotes: 2

PawZaw
PawZaw

Reputation: 1438

Look here: https://learn.microsoft.com/pl-pl/dotnet/csharp/language-reference/keywords/where-generic-type-constraint

You have two options:

  • Create non-generic class Foo and make Foo<T> implement it (just like IEnumerable<T> implements IEnumerable)

  • Make Bar use two generics instead of one

    class Bar<T1,T2> where T1: Foo<T2>

Upvotes: 3

Klaus G&#252;tter
Klaus G&#252;tter

Reputation: 11977

Assuming Question is meant to be Foo<> you could use:

class Bar<T, T2> where T : Foo<T2> { }

Upvotes: 1

Related Questions