Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Parent For Generic Class

Tags:

c#

generics

I am using a fictional example for this. Say, I have a Widget class like:

abstract class Widget
{
Widget parent;
}

Now, my other classes would be derived from this Widget class, but suppose I want to put some constraint in the class while defining the derived types such that only a particular "type" of widget can be parent to a particular type of Widget.

For example, I have derived two more widgets from the Widget class, WidgetParent and WidgetChild. While defining the child class, I want to define the type of parent as WidgetParent, so that I dont have to type cast the parent every time I use it.

Precisely, what I would have liked to do is this:

// This does not works!
class Widget<PType>: where PType: Widget
{
    PType parent;
}

class WidgetParent<Widget>
{
    public void Slap();
}

class WidgetChild<WidgetParent>
{
}

So that when I want to access the parent of WidgetChild, instead of using it this way:

WidgetParent wp = wc.parent as WidgetParent;
if(wp != null)
{
    wp.Slap();
}
else throw FakeParentException();

I want to use it this way(if I could use generics):

wc.parent.Slap();
like image 661
nullDev Avatar asked Nov 04 '08 06:11

nullDev


People also ask

What is generic class with example?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

What is a generic class in C #?

Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.

Can generic class be inherited?

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

What is meant by generic class?

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.


1 Answers

You should be able to use the code you've got by still having the non-generic class Widget and making Widget<T> derive from it:

public abstract class Widget
{
}

public abstract class Widget<T> : Widget where T : Widget
{
}

You then need to work out what belongs in the generic class and what belongs in the non-generic... from experience, this can be a tricky balancing act. Expect to go back and forth a fair amount!

like image 73
Jon Skeet Avatar answered Sep 20 '22 06:09

Jon Skeet