Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET 4.0 and Generics

I was wondering if anyone could tell me if this kind of behaviour is possible in C# 4.0

I have an object hierarchy I'd like to keep strongly typed. Something like this

class ItemBase {}

class ItemType<T> where T : ItemBase 
{
   T Base { get; set; }
}


class EquipmentBase : ItemBase {}
class EquipmentType : ItemType<EquipmentBase> {}

What I want to be able to do to have something like this

ItemType item = new EquipmentType();

And I want item.Base to return type ItemBase. Basically I want to know if it's smart enough to strongly typed generic to a base class without the strong typing. Benefit of this being I can simply cast an ItemType back to an EquipmentType and get all the strongly typedness again.

I may be thinking about this all wrong...

like image 823
Mr Snuffle Avatar asked Mar 11 '26 03:03

Mr Snuffle


1 Answers

You're talking about covariance which would allow you to do:

ItemType<object> item = new EquipmentType();

You couldn't do this in C# 4 because of the following reasons:

  1. Generic covariance only works on interfaces, arrays, and delegate types, not base classes
  2. Your ItemType class uses T as an in/out type parameter meaning it receives a T and also returns a T.

Number 2 is the main issue because if it were allowed, then the following code would have to be compilable, yet fail at runtime.

// this will not work
ItemType<object> item = new EquipmentType();
item.Base = new Object(); // this seems ok but clearly isn't allowed

Covariance and Contravariance FAQ

like image 158
Josh Avatar answered Mar 12 '26 16:03

Josh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!