views:

500

answers:

2

Suppose we are creating a generic control in .NET. E.g. a tree. I don't understand why people use this generic type definition

Control<T>

when in Object Oriented Programming I can use an abstract class or an interface:

Control<IItem> or Control<BaseClass>

So the only thing to do is that, their types must derive from that base class or implement the interface. Does it mean, that generic types are more convenient, because you I don't have to implement or inherit anything?

+2  A: 

Because in your case of a tree control, defining a generic Tree control would mean that Tree items can be of any type (you can also add certain constrains).

When instantiating a control, you would of course have to declare your item type (like in your second code examples with IItem and BaseClass).

If your Tree control wouldn't be a generic type, you would have to create several controls for each item type.

Why not just use interface/abstractBase type?
If you would just use an interface/abstract as your Item concrete class, you would be constrained by it's definition. You'd only see it's properties and methods. With generic Tree control and whatever item type, you're still able to access all item's properties and methods regardless of its interface implementation or parent class inheritance...

Robert Koritnik
Yes thank you, that's what i wanted to hear.
PaN1C_Showt1Me
But I have 1 more question, what if I want to constraint the type T to have Parent and Children property and I don't use an interface. Is it possible?
PaN1C_Showt1Me
@stefan - constraints have to be expressed via interfaces, apart from a few simple things: it is a value type (`where T : struct`), or a reference type (`where T : class`), or that it has a default constructor (`where T : new()`)
Daniel Earwicker
@stefan: of course you can do that as well without an interface as long as you define a class with those two properties and your item classes inherit from it. But it's generally much easier to use interface, because a class can implement multiple interfaces but inherit only one.
Robert Koritnik
...inherit only one class. Sorry.
Robert Koritnik
+3  A: 
Artem Barger
OK now I understand the difference, Thank you very much.
PaN1C_Showt1Me
Glad, I made a bit clear for you.
Artem Barger