Re: narrowing conversions with arrays
From: John Wood (spam_at_isannoying.com)
Date: 04/15/04
- Next message: TT \(Tom Tempelaere\): "[ty] Re: PInvoke, how to marshal a UINT*"
- Previous message: Will Pittenger: "Re: Some .NET XML documentation tags are not recognized when I update my solution's documentation"
- In reply to: Jon Skeet [C# MVP]: "Re: narrowing conversions with arrays"
- Next in thread: Erik Frey: "Re: narrowing conversions with arrays"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 15 Apr 2004 21:00:19 GMT
ok slight confusion, sorry.
Base[] bases = new Base[1];
bases[0] = new Inherited();
inheriteds = (Inherited[])bases;
Causes the runtime error. You changed it to:
Base[] bases = new Inherited[1];
bases[0] = new Inherited();
inheriteds = (Inherited[])bases;
Which does work.
So the compiler doesn't raise an error because bases can contain an instance
of an array of any type derived from Base -- and the compiler doesn't know
which particular instance it contains.
Makes sense....
Learnt something else while playing with this... the following code produces
this exception:
An unhandled exception of type 'System.ArrayTypeMismatchException' occurred
Attempted to store an element of the incorrect type into the array.
class Base { }
class Base2 : Base { }
class Inherited : Base { }
Base[] bases;
Inherited[] inheriteds;
Base[] bases = new Inherited[1];
bases[0] = new Base2();
inheriteds = (Inherited[])bases;
"Jon Skeet [C# MVP]" <skeet@pobox.com> wrote in message
news:MPG.1ae9025c1d406b0598a6c1@msnews.microsoft.com...
> John Wood <spam@isannoying.com> wrote:
> > What ver of .net are you running?
> > When I run the code on 1.0 it causes a runtime error. Perhaps it's fixed
in
> > 1.1.
>
> It's certainly fine on 1.1, but I'm surprised it fails on 1.0. What
> error are you getting? Are you running the *exact* code I posted?
>
> --
> Jon Skeet - <skeet@pobox.com>
> http://www.pobox.com/~skeet
> If replying to the group, please do not mail me too
- Next message: TT \(Tom Tempelaere\): "[ty] Re: PInvoke, how to marshal a UINT*"
- Previous message: Will Pittenger: "Re: Some .NET XML documentation tags are not recognized when I update my solution's documentation"
- In reply to: Jon Skeet [C# MVP]: "Re: narrowing conversions with arrays"
- Next in thread: Erik Frey: "Re: narrowing conversions with arrays"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|