A generic class that inherits its generic type

Possible duplicates:
Why is C ++ not generated from one of the parameters of the type type, as they can in C ++ templates? In C # 4.0, is it possible to derive a class from a parameter of a general type?

I am trying to create a generic class that inherits its generic type (in 1.Attempt). It seems like this is impossible. But in another attempt, I have to drop the object. Any design solution to this problem?

// #1 Attempt public interface IFoo { } public class Generic<T> : T { } public void play () { IFoo genfoo = new Generic<IFoo> (); } 

.

 // #2 Attempt. Castable solution public interface IAnything { } public interface IFoo2 : IAnything { } public class Generic2<T> : IAnything { } public void play2 () { IFoo2 genFoo = (IFoo2) new Generic2<IFoo2> (); } 
+4
generics c #
source share
3 answers

I do not see the point in the code that you indicated in attempt # 1. Why do you inherit a class and then pass the same class as the general parameter.

However, shared inheritance is supported, but it is done differently, please check this link, this may give you an idea: General inheritance

Hope this helps.

+1
source share

What you do is striking a common goal.

How can I just use something like this:

 Generic<int> intgen = new Generic<int>(); // Impossible 

The generic problem defines behavior that is independent of type . your generic type is type specific as it must inherit . Generic is used to encapsulate functionality that cannot be expressed in inheritance while you mix two - and I can tell you that it won't be a good combination .

0
source share

You cannot do this because T in the generic definition is a type definition, not a real class. I'm not sure what you are trying to achieve, because, in my opinion, your problem can be solved by simple inheritance. If you are trying to add some kind of behavior to your class, then you can just use the general one and get from this:

 public class Behavior<T> { ... } public class DerivedBehavior<T> : Behavior<T> { ... } 
0
source share

All Articles