In C# and also Java, what's the relationship between Object[] and String[]? -


i started think of problem , can't find answer. following code compiles , executes expected

object[] test = new string[12]; 

however, don't know why.

i mean, should consider string[] derived class of object[]? think in c#, every array instance of array class. if array generic, should array<t>, , array<string> can assigned array<object>, doesn't make sense. remember interface can use in/out keyword.

and in java, i'm not sure, still feel weird. why different types of references can possibly assigned each other when don't have super-sub class relationship?

can explain little?

thanks lot!

it's because reference type arrays support covariance in both java , c#. means every write reference type array has checked @ execution time, make sure don't write wrong type of element :(

don't forget both java , c# (and .net in general) started off without generics. if had had generics start with, life have been different.

note both java , c# support generic variance now, in rather different ways. example in c# 4 can write:

ienumerable<string> strings = // string sequence here ienumerable<object> objects = strings; 

but can't write

ilist<string> strings = // string list here // compile-time error: ilist<t> isn't covariant in t ilist<object> objects = strings; 

this wouldn't safe, because can add ilist<t> taking items it.

this big topic - more details, see eric lippert's blog series.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -