I’ve recently tried to simplify some of my code by using generics where possible.
However, this particular example has me stumped… Yet it looks so innocent!
Here’s the offending code (simplified).
public static void Updater(CommodityVO vo)
{
// Update something
}
public static void BulkUpdate<T>(IEnumerable<T> vos)
{
foreach (var vo in vos)
{
Updater(vo);
}
}
In Visual Studio, the ‘vo’ in ‘Updater(vo)’ gets a squiggly line and the compiler (VS2010) reports:
Argument type ‘T’ is not assignable to parameter type CommodityVO
<T> behaves the same as IEnumerable<T>I have worked around this issue for now. But I’d like to know why this was rejected… Especially since it all looks fine to me. What am I missing?
All help appreciated.
What you’re looking for here is a generic constraint. The type
Tneeds to be constrained to be an instance ofCommodityVOWithout this generic constraint the C# compiler has no information on the generic parameter
Tand must assume the worst case thatTis instantiated asobject. The typeobjectis not compatible withCommodityVOand hence it issues an error. By adding the constraint you are limiting the valuesTcan be instantiated as toCommodityVOor types deriving fromCommodityVOwhich means the conversion toCommodityVOis legal and hence allowed.