[Mono-list] Generics Conversions
Ricky Clarkson
ricky.clarkson at gmail.com
Mon Feb 23 08:10:36 EST 2009
I'll explain this by jumping to Java for a moment. Java's arrays (but not
its generics) are broken in that they do what you want, which is broken:
Number[] numbers = new Double[1];
numbers[0] = 5;
This causes an ArrayStoreException at runtime. C#'s arrays and generics are
not broken in this manner, and will give a compile error instead.
A list of strings is not a list of objects, as long as a list is mutable.
C# 4 adds covariance and contravariance.
IEnumerable<object> objects = new List<string>(); will be valid.
List<object> more = new List<string>(); will not be valid. List will still
be declared as List<T>, and IEnumerable will be interface IEnumerable<out T>
{ stuff }.
Right now I'd use IEnumerable<object> objects = stringList.Select(x =>
(object)x); or if you must have List<>, List<object> objects =
stringList.Select(x => (object)x).ToList();
The advantage of the IEnumerable is that no actual copying is done.
Have fun,
Ricky.
2009/2/23 Sascha Leib <sascha.leib at gmail.com>
> Hello all,
>
> I noticed one behaviour when using Generics:
>
> List<String> StringList = new List<String>();
>
> List<Object> ObjectList = (StringList as List<Object>); //
> Error
>
> The error message is:
> Program.cs(14,51): error CS0039: Cannot convert type
> `System.Collections.Generic.List<string>' to
> `System.Collections.Generic.List<object>' via a built-in conversion
>
> Is that a wanted behaviour? Or am I missing something? This really stops
> me from using more Generics at the moment :-/
>
> /sascha
>
> PS: At least it is consistent with how VS handles it...
>
>
> _______________________________________________
> Mono-list maillist - Mono-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-list/attachments/20090223/cb3176e8/attachment.html
More information about the Mono-list
mailing list