Re: returning a generic array




"ndac" <ndac@xxxxxxxx> wrote in message
news:460188ac$0$90270$14726298@xxxxxxxxxxxxxxxxxx
Hello,

assume I have the following:

public interface X<E> {
...
E[] toArray();
}
public class XImp<E> {
E[] toArray(){
E[] a = (E[])new Object[N];
...
return a;
}
}

using this like this gives me a bad cast exception?
X<String> x = new X<String>();
...
String[] a = x.toArray();
(or String[] a = (String[])x.toArray();)

what am I doing wrong here?


Don't forget: .toArray() must return Object[]. It would be nice to
be able to cast from Object[] to String[] but you can't.

You can cast the items though after storing them in Object[]
though.

Object[] obj = x.toArray();
String[] str = null;
str[0] = (String)obj[0];

Of course the cast could be wrong at runtime. You have to make
sure that all the objects in obj can be represented by String.

Seems to me that it would be nice to have .toArray() return the
correct type someday. But even if the cast you tried to do would
work, you'd still have the same problem at runtime if one of the
objects was not capable of being represented by String. I don't
think it's a trivial fix.





.



Relevant Pages

  • Re: Invalid CastException with SqlDBType
    ... Add(string*, SqlDbType, int, string**) ... The DateTime.Now is trying to cast into a int. ... not in Sql set up the column as identity and let it seed itself. ... > update a MS SQL Database with a stored procedure. ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: Porting up to VC++ 2005
    ... Since you are dealing with strings that contain file names, ... characters, but that's a different question to be handled in a different way. ... done, which should be unnecessary, it should be an LPTSTR cast, which ... It only applies to string and ...
    (microsoft.public.vc.mfc)
  • Re: Confused about using Reflection to examine a collection
    ... the precise type that Reflection is saying it is. ... say that 'obj' is actually a custom collection. ... If it were a basic type, such as 'string' then I would do a cast like this: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: TRUE and FALSE are treated differently
    ... No -- you can't echo a boolean in PHP. ... the boolean is implicitly cast to a string. ... If you look up the manual on type casting, you'll find that FALSE is cast to an empty string, and TRUE is cast to a non-empty string. ...
    (comp.lang.php)
  • Re: Error whilst processing ORDER BY clause
    ... My guess would be that you need to CAST it to a boolean since it is assuming ... > We receieve the error "Error whilst processing ORDER BY clause in the SQL ... name in the clause to reference a string or int data type it also succeeds, ... Can we use a CAST ...
    (microsoft.public.exchange2000.misc)