mono - Covariance broken in C# arrays? -


consider following generic interface itest covariant type parameter t, generic class test implementing interface, , class a , subclass b:

interface itest<out t>  {       t prop{ get;} } class test<t> : itest<t> {         public t prop{ {        return default(t);         }} } class {     } class b: {     } 

the following code compiles no errors throws runtime exception system.arraytypemismatchexception:

itest<a>[] = new itest<a>[1]; a[0] = new test<b>(); //<-- throws runtime exception 

but code works fine:

itest<a> r = new test<b>(); 

this has tested on mono 2.10.2 (unity3d 4.1). think somehow related broken covariance in arrays (see http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx).

i not clear why type-check happening when array slot assigned not taking covariance account.

i have compiled , tested given code in vs2010 using .net 4 on windows 7 , works fine, not give runtime exception, seem problem either mono or unity related.

with given code hard make assumptions problem is. exact type of exception , other test cases (ie variations not use interfaces) narrow down exact problem, matter mono|unity community solve.

as being linked article, unrelated.

what article describing following situation:

class { } class b: { } class c: { }  a[] = new b[1]; a[0] = new c(); //<-- throws arraytypemismatchexception 

to simplify eric saying in article:

a variable can hold array of type inherits a.

a assigned array of b, array of b.

when user tries assign new c element of a, there type mismatch because array of b, assigning c element of equivalent trying assign new c variable holds b so:

b b = new c(); 

a similar issue arise assigning array of c.

however, defined being able hold array of a, user assign array of a, allow accept both values of b , c.

it because of code in question appears related problem, in fact not because assigned array of itest, meeaning should able store types of itest , runtime error being thrown stems error in either mono or unity's runtime.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -