Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit from a generic parameter?

Tags:

I'm basically wanting to do this:

class UILockable<T> : T     where T : UIWidget { } 

However, this doesn't work. I've seen people recommend that you do this:

class UILockable<T>     where T : UIWidget {     private T _base; } 

This would require me to override each function UILockable would need and forward it to T. This is impossible since T may derive from UIWidget and have unique abstract/virtual methods of its own.

Is there no way to simply inherit from T?

like image 829
void.pointer Avatar asked Jun 15 '10 18:06

void.pointer


People also ask

Can we inherit from generic class?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

What is a generic type parameter?

Generic Methods A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

How do you indicate that a class has a generic type parameter?

A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.

What is generic parameters in C#?

Generics were added in C# 2.0. Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types that they store or use. A generic collection class might use a type parameter as a placeholder for the type of objects that it stores.


2 Answers

You can't inherit from the generic type parameter. C# generics are very different from C++ templates. Inheriting from the type parameter requires the class to have a completely different representation based on the type parameter, which is not what happens with .NET generics. They are identical at the IL and native level (for all reference type arguments).

like image 178
mmx Avatar answered Sep 22 '22 23:09

mmx


Think about it this way: When Type B inherits from type A, you're declaring that B is similar to A (where similarity means that you can use B everywhere you expect to use A). Now because such similarity is not symmetric you have that B is similar to A but A is not similar to B. Furthermore, B and C can both be similar to A (i.e. they both descend from A) without being similar to each other.

So what you want to declare is that Unlockable is similar to everything that is similar to UIWidget, but that's impossible because type similarity is not transitive (i.e. if B is similar to A and C is similar to A you can't say B is similar to C).

like image 26
Rodrick Chapman Avatar answered Sep 24 '22 23:09

Rodrick Chapman