Home > other >  Generic type where T is derived from a generic type
Generic type where T is derived from a generic type

Time:12-31

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.

CodePudding user response:

Look here: https://docs.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>

CodePudding user response:

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

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

CodePudding user response:

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> { }
  •  Tags:  
  • c#
  • Related