ArrayList to array of strings

  • Thread starter Thread starter A.M
  • Start date Start date
A

A.M

Hi,


What would be the fastes way to convert an ArrayList to an array of string ?
I am trying to avoid running a loop.


Thanks,
Ali
 
A.M said:
What would be the fastes way to convert an ArrayList to an array of string ?
I am trying to avoid running a loop.

I believe this is what you're looking for:

string[] arr = arrayList.ToArray(typeof(string)) as string[];
 
Should be :

string[] arr = (string[])arrayList.ToArray(typeof(string)) ;

right?


C# Learner said:
A.M said:
What would be the fastes way to convert an ArrayList to an array of string ?
I am trying to avoid running a loop.

I believe this is what you're looking for:

string[] arr = arrayList.ToArray(typeof(string)) as string[];
 
A.M said:
Should be :

string[] arr = (string[])arrayList.ToArray(typeof(string)) ;

right?

I don't see why -- both ways cast to an array of strings.

I prefer to use 'as' when I know for certain that what I'm casting is of
the specified type.

In this case, ArrayList.ToArray() would never return anything but a
string array -- if there was a problem converting an element to a
string, an exception would be thrown from within the method, and it
wouldn't return. Therefore, you know for certain here that the return
value will be of type 'string[]'.
 
Thanks for reply.

C# Learner said:
A.M said:
Should be :

string[] arr = (string[])arrayList.ToArray(typeof(string)) ;

right?

I don't see why -- both ways cast to an array of strings.

I prefer to use 'as' when I know for certain that what I'm casting is of
the specified type.

In this case, ArrayList.ToArray() would never return anything but a
string array -- if there was a problem converting an element to a
string, an exception would be thrown from within the method, and it
wouldn't return. Therefore, you know for certain here that the return
value will be of type 'string[]'.
 
Should be :
string[] arr = (string[])arrayList.ToArray(typeof(string)) ;

right?

I don't see why -- both ways cast to an array of strings.

I prefer to use 'as' when I know for certain that what I'm casting is of
the specified type.

In this case, ArrayList.ToArray() would never return anything but a
string array -- if there was a problem converting an element to a
string, an exception would be thrown from within the method, and it
wouldn't return. Therefore, you know for certain here that the return
value will be of type 'string[]'.

You should only use "as" if I want to test the returned value in the next
statement against null because this is the sense of "as".
A cast should be used when you are sure which type it is.
 
codymanix said:
You should only use "as" if I want to test the returned value in the next
statement against null because this is the sense of "as".

No, that's just one common use.
A cast should be used when you are sure which type it is.

Why? If you're sure, it doesn't matter which you use.

as is slightly faster than a cast, and in some cases is more readable
than using a cast.

I would normally use a cast, but I don't think there's anything really
wrong with using as instead. The only downside is that if you're wrong
about the type, you'll end up with a NullReferenceException instead of
an InvalidCastException.
 
You should only use "as" if I want to test the returned value in the
next
No, that's just one common use.


Why? If you're sure, it doesn't matter which you use.

as is slightly faster than a cast, and in some cases is more readable
than using a cast.

No, "as" is not faster than a cast.
But if you are querying the type and then determine wheather to cast or not
is a difference:

if (a is MyClass)
{
b = (MyClass)a;
}

Because the system has to determine the type twice here.

But if you do b = a as MyClass or b = (MyClass)a there should be no
difference in speed.
I would normally use a cast, but I don't think there's anything really
wrong with using as instead. The only downside is that if you're wrong
about the type, you'll end up with a NullReferenceException instead of
an InvalidCastException.

The problem is the the nullreferenceexception can occur very late in the
program or maybe never.
The program does not behave as it should and you don't know why. It is very
diffycult to tell where in the program the error has its origin then.
But when you use a cast instead you know immediately when there is someting
wrong.

The meaning of a cast is "I know that it is that type and if not an error
immediately reports that there is someting wrong".

The meaning of as is "Maybe it is the type I assume, I will immediately test
if for null to determine if it really was the type I assumed".
 
codymanix said:
No, "as" is not faster than a cast.

Um, yes it is (on .NET 1.1, at least). Not by very much, but it is.

See

http://groups.google.com/groups?selm=MPG.1acca34b9f6b3a7d98a485%
40msnews.microsoft.com&rnum=4

(aka http://tinyurl.com/2o44v) for evidence of this.
But if you are querying the type and then determine wheather to cast or not
is a difference:

if (a is MyClass)
{
b = (MyClass)a;
}

Because the system has to determine the type twice here.

Yes - that's *really* slow. That doesn't mean that a cast itself is as
quick as using "as", however.
But if you do b = a as MyClass or b = (MyClass)a there should be no
difference in speed.

Except there is, demonstrably. What makes you think there shouldn't be?
The problem is the the nullreferenceexception can occur very late in the
program or maybe never.

That's true, if *and only if* you don't then immediately dereference
the result.
The program does not behave as it should and you don't know why. It is very
diffycult to tell where in the program the error has its origin then.
But when you use a cast instead you know immediately when there is someting
wrong.

Sure. Using as and then immediately dereferencing the value lets you
know *almost* as immediately, and pretty much just as usefully though.
In some cases, it gives you more readable code - and in those cases, I
would have no problem with using "as".
The meaning of a cast is "I know that it is that type and if not an error
immediately reports that there is someting wrong".

The meaning of as is "Maybe it is the type I assume, I will immediately test
if for null to determine if it really was the type I assumed".

No, the meaning of "as" is (from the C# specification):

<quote>
The as operator is used to explicitly convert a value to a given
reference type using a reference conversion or a boxing conversion.
Unlike a cast expression, the as operator never throws an exception.
Instead, if the indicated conversion is not possible, the resulting
value is null.
</quote>

As I said, a common *use* of that is to then immediately test for
nullity, but it's by no means required.
 
But if you do b = a as MyClass or b = (MyClass)a there should be no
Except there is, demonstrably. What makes you think there shouldn't be?

Both "as" and a cast does nothing then for testign for the type except that
a cast throws on error and "as" simply returns null.
Maybe the current implementation is that way but theoretically both should
be the same speed.
That's true, if *and only if* you don't then immediately dereference
the result.

DoIt(object obj)
{
StronglyTypedlistOrArray.Add( obj as string );
}

You will, at very late time notice that some values in the list are null.
you don't know why. it could be everywhere in the program.
After hours of debug you find this piece of code where you never thought
what would happen is object is not a string.
The worst errors are such that get swallowed and show up only under very
certain circumstances.

Thats why in C one should always set deleted pointers to 0 so that the next
access immediately produces an error.
otherwise bugs that are very hard to find are introduced.
Sure. Using as and then immediately dereferencing the value lets you
know *almost* as immediately, and pretty much just as usefully though.
In some cases, it gives you more readable code - and in those cases, I
would have no problem with using "as".

I agree that the excessive parenthese usage when casting can be very
unreadable.
((Foo)list).DoFoo();
vs.
listas Foo.DoFoo();
No, the meaning of "as" is (from the C# specification):

<quote>
The as operator is used to explicitly convert a value to a given
reference type using a reference conversion or a boxing conversion.
Unlike a cast expression, the as operator never throws an exception.
Instead, if the indicated conversion is not possible, the resulting
value is null.
</quote>

As I said, a common *use* of that is to then immediately test for
nullity, but it's by no means required.

Yes whatever the docs say, imho using "as" without explicit test for nullity
can be dangerous.

However this is more personal opinion and I do not want to start a language
feature war with you..
"My language feature is much better than yours"

:)
 
codymanix said:
Both "as" and a cast does nothing then for testign for the type except that
a cast throws on error and "as" simply returns null.
Maybe the current implementation is that way but theoretically both should
be the same speed.

That sounds very much like the normal quote:

"In theory, theory and practice should give the same results. In
practice, they don't."

Note that they're using different IL instructions, for one thing...
DoIt(object obj)
{
StronglyTypedlistOrArray.Add( obj as string );
}

You will, at very late time notice that some values in the list are null.

Yes, because that's not immediately dereferencing the result.
you don't know why. it could be everywhere in the program.
After hours of debug you find this piece of code where you never thought
what would happen is object is not a string.
The worst errors are such that get swallowed and show up only under very
certain circumstances.

Thats why in C one should always set deleted pointers to 0 so that the next
access immediately produces an error.
otherwise bugs that are very hard to find are introduced.

That doesn't address my point that if you *are* immediately
dereferencing the result, using "as" has no significant debugging
downside and can end up being more readable.
Sure. Using as and then immediately dereferencing the value lets you
know *almost* as immediately, and pretty much just as usefully though.
In some cases, it gives you more readable code - and in those cases, I
would have no problem with using "as".

I agree that the excessive parenthese usage when casting can be very
unreadable.
((Foo)list).DoFoo();
vs.
listas Foo.DoFoo();


Well, I'd still have some more brackets than that:

(list as Foo).DoFoo();

but that's still simpler to read than the first version.
Yes whatever the docs say, imho using "as" without explicit test for nullity
can be dangerous.

It can be, if it's not used carefully, yes - as can almost anything.

However:

o Sometimes null is actually the result you want
o Often you immediately dereference the result anyway, in which case
there's no real problem
 
Both "as" and a cast does nothing then for testign for the type except
that
That sounds very much like the normal quote:

"In theory, theory and practice should give the same results. In
practice, they don't."

Note that they're using different IL instructions, for one thing...


I believe you but performance wasn't really the issue here.

null.

Yes, because that's not immediately dereferencing the result.


I didn't claimed that I only wanted to show you the dangers..

That doesn't address my point that if you *are* immediately
dereferencing the result, using "as" has no significant debugging
downside and can end up being more readable.
Yes.


It can be, if it's not used carefully, yes - as can almost anything.

However:

o Sometimes null is actually the result you want
o Often you immediately dereference the result anyway, in which case
there's no real problem

Sure! But I use "as" only if the type of the object determines the flow of
control in my application:

T t = a as t
if (t!=null)
{
t.Fubar();
}

And sometimes when I want to store the variable only if it is of a certain
typ I use as because:

if (a is T)
t = (T)a
else
t=null;

is the same as

t = a as T;

But if Iam sure that the object should/must be of a certain type I use a
cast so if it is not the type I expected I get an appropriate error.
What if your customer tells you your app crashed with a
NullReferenceException at line xxxx?
Then you don't know wheather the problem comes from the cast or the value
already was null before the as-conversion.

However just my personal opinion.
 
What if your customer tells you your app crashed with a
NullReferenceException at line xxxx?
Then you don't know wheather the problem comes from the cast or the value
already was null before the as-conversion.

That is indeed a problem - it's not an issue when debugging, but the
exception is definitely less useful when logged.

However, I can't honestly say I've actually *ever* run into this as a
problem where I really expected a cast to work. (At least, I can't
remember it ever happening.)

Of course, when generics arrive a lot of this discussion will be
pointless :)
 
codymanix said:
You should only use "as" if I want to test the returned value in the next
statement against null because this is the sense of "as".
A cast should be used when you are sure which type it is.

I couldn't agree less. As I see it, 'as' is the one to use when you're
sure of which type it is. I don't see how you can think otherwise, due
to the nature of the two.

This is my understanding of it:

foo = (string)bar; // if not a string, throw and exception and do *not*
// make the assignment

foo = bar as string; // trust the programmer that this is correct, but
// give null anyway if this isn't the case, or else
// we might encounter unpredictable behaviour

Think about it - if 'as' didn't return 'null' on failure, what exactly
*would* it return?
 
You should only use "as" if I want to test the returned value in the
next
I couldn't agree less. As I see it, 'as' is the one to use when you're
sure of which type it is. I don't see how you can think otherwise, due
to the nature of the two.

Huh? If you are sure about the type you can safely cast. If you assumption
is wrong then your program would be in trouble when the cast would silently
do nothing - but a cast is good here because it throws an exception to
notify that something unpredictible happened.

You should never use exceptions for control flow so using a cast so see
wheather a variable has a certain type is certainly a very bad idea.

try
{
a = (T)b;
}
catch
{
a=null;
}

Would be a very stupid thing. a cast should only be used when you are sure
about the type and you assume that the conversion will be successful.

If you use "as" you are not sure about the type. so you try to convert the
variable using "as" and test wheather is is null or not.

Use a cast when you assume this type and "as" when your decision flow
depends on the actual type.
This makes you intend clear and protects you from mistakes.
This is my understanding of it:

foo = (string)bar; // if not a string, throw and exception and do *not*
// make the assignment

foo = bar as string; // trust the programmer that this is correct, but
// give null anyway if this isn't the case, or else
// we might encounter unpredictable behaviour

Think about it - if 'as' didn't return 'null' on failure, what exactly
*would* it return?

I cannot follow you. Your thoughts are illogical.
 
codymanix said:
Huh? If you are sure about the type you can safely cast. If you assumption
is wrong then your program would be in trouble when the cast would silently
do nothing - but a cast is good here because it throws an exception to
notify that something unpredictible happened.

This is precisely why you shouldn't use 'as' when you're unsure about
the type. The above just qualifies my argument.
You should never use exceptions for control flow so using a cast so see
wheather a variable has a certain type is certainly a very bad idea.

I don't think that's the general idea to do with exceptions thrown when
casting. Exceptions here serve as a safe-guard.
try
{
a = (T)b;
}
catch
{
a=null;
}

Would be a very stupid thing.

Indeed, and it is certainly wasn't an argument of mine.
a cast should only be used when you are sure
about the type and you assume that the conversion will be successful.

If you use "as" you are not sure about the type.

Except in the case of me and others who use 'as' when they *are* sure :-)
so you try to convert the
variable using "as" and test wheather is is null or not.

No -- I normally use 'as' when I am sure and do *not* need to test the
end result against 'null'.
Use a cast when you assume this type and "as" when your decision flow
depends on the actual type.
This makes you intend clear and protects you from mistakes.


I cannot follow you. Your thoughts are illogical.

My point, that I'll re-iterate here, was that 'as' *has* to return
something. e.g.: when the programmer cannot *guarantee* to the compiler
that (a is b), 'a' must eventually be assigned a value, whether in the
case of success or failure.
 
Huh? If you are sure about the type you can safely cast. If you
assumption
This is precisely why you shouldn't use 'as' when you're unsure about
the type. The above just qualifies my argument.

So when you use "as" when you _are sure_ about the type, when do you use a
cast?
Do you use a cast then if you are unsure about the type?
No -- I normally use 'as' when I am sure and do *not* need to test the
end result against 'null'.

And if the type is not what you expect you have a null value
which can under circumstances very hard to trace back.
My point, that I'll re-iterate here, was that 'as' *has* to return
something. e.g.: when the programmer cannot *guarantee* to the compiler
that (a is b), 'a' must eventually be assigned a value, whether in the
case of success or failure.

In Delphi it was possible for a Ctor to return null on failure, so you never
knew wheather the statement
a = new A(); produced a valid object or null. What a stupid feature.
In C# a Ctor would throw an exception if an _unexpected_ error occurred. The
same is true with cast vs. 'as'.
 
codymanix said:
So when you use "as" when you _are sure_ about the type, when do you use a
cast?
Do you use a cast then if you are unsure about the type?

If I ever felt, for whatever reason, that the object might not be of the
type I presume, I'd use the parentheses cast (and let the exception
bubble-up); else, I'd use 'as'.

<snip>

Another question arises out of this -- *when* is one ever unsure of the
type, in practise?

I find that the closest to being unsure of the type, in practise, will
be a case like this:

void DoSomething(object o)
{
Type t = o.GetType();
if (t == typeof(FirstType)) {
HandleFirstType(t as FirstType);
} else if (t == typeof(SecondType)) {
HandleSecondType(t as SecondType);
}
}

Comments?
 
The various places you can get into trouble are event handlers, writing
library code that takes an object as you show below, but does something
custom with a more strongly typed version, code that is trying to be
generic (will be solved when generics are actually available), or doing
anything with plug-ins where you have to dynamically load the type.

Note the 'is' keyword is the most readable way to determine if an object
is of a particular type. The as keyword is the safest way to convert objects
that are of an object type. And the 'is' keyword followed by a cast is
required if you need to unbox a value type.

I never blatantly cast and throw an exception. Throwing exceptions uber
kills performance. While exceptions are the way of errors in the .NET world
and I'll use them sparingly in library code to notify the users of an error,
I'll
always try to provide an alternate method for the savvy user that would
rather use the non throwing version. You can check my blog entry on various
methods of parsing strings into integers, how much performance difference there
is between throwing vs not throwing, and how much debate there is still over
which methods should be used.

Performance: Different methods for testing string input for numeric values...
and
Following up on the benefits of continued use of int.Parse...
 
Back
Top