0

when replacing arrays of type A (A[]) by generic lists (List <A>), combined with following inheritance

A : B (A is inherited from B)

and having by ref parameter, the following code doesn't compile any more :

class MyGenericList:
{
  
  HandleListB( ref List<B> list)
  {
    ..
  }
  HandleListA( ref List<A> list)
  {
     ... 
     HandleListB( ref list )
  }
}

results to: Error CS1503 Argument 2: cannot convert from 'ref System.Collections.Generic.List' to 'ref System.Collections.Generic.List'

whereas this code gets compiled properly:

class MyArray:
{
  
  HandleListB( ref B[] list)
  {
    ..
  }
  HandleListA( ref A[] list)
  {
     ... 
     HandleListB( ref list )
  }
}
  • can anyone explain the different inheritance behaviour between Generic Lists and Arrays in this case?
  • and is there a way to solve this problem (the example simplifies the real problem, there are many imvovations of HandleListB( ref list ) throughout my whole project, resulting in many compilation errors when replacing arrays by generic lists..) ?
  • 1
    Is `B` inheriting from `A` or vice versa? – haim770 Aug 15 '22 at 07:53
  • A is inherited from B – Daniel Devo Aug 15 '22 at 07:59
  • 2
    This setup can *only* work with arrays, and nothing else, and even in the case of arrays you get hidden costs with the runtime having to verify at every step that what you're doing is safe. It's likely that if you want this code to be maintainable going forward you'll have to rewrite it entirely (splitting cases of mutable vs. immutable access and using `IEnumerable` or `IReadOnlyList` for the latter, since that offers covariance). Alternately, move to a common base class and only use that, casting as necessary at the edges. – Jeroen Mostert Aug 15 '22 at 08:21
  • ok, thanks for your comments. i think i understand that covariant rule is safe for immutable Arrays, so this is the reason why ```A[]``` is working, but ```List``` not? – Daniel Devo Aug 15 '22 at 13:21

0 Answers0