[Mono-list] Generics Conversions

Chris Howie cdhowie at gmail.com
Mon Feb 23 08:23:41 EST 2009

On Mon, Feb 23, 2009 at 7:58 AM, Sascha Leib <sascha.leib at gmail.com> wrote:
> 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 :-/

To further explain what the others have said, consider this C# code:

List<string> stringList = new List<string>();
stringList.Add("a string");
List<object> objectList = (List<object>) stringList;

So far, so good, right?  But what about:


Wait, that's a compile-time error, right?  No, it's not.  The
signature of the Add method will be "public void
List<object>.Add(object item);" and an integer can be boxed to satisfy
this condition.  This would add a non-string to a List<string>.  The
only type-safe way to prevent this from happening is to prevent a cast
from List<string> to List<object>.

As a side note, you should not use the "(object as type)" form of
casting in this scenario -- use "(type) object" instead.  The former
will succeed regardless of the type of the object and return null,
causing any usage of the result of the cast to throw a
NullReferenceException.  The latter will immediately throw a
ClassCastException, which is a good indication of what is going on.
Using the "as" cast would result in cryptic errors and time wasted
debugging trying to figure out why the original object is null when in
fact it's just not of the requested type.

Chris Howie

More information about the Mono-list mailing list