Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Array.Reverse(myCharArray) and not myCharArray=myCharArray.Reverse?

Tags:

arrays

c#

reverse

I'm new to programming. I'm learning c# through Bob Tabors videos on Channel 9.

Can you explain why we cannot do something like this:

string mijnVoornaam = "Remolino";
char[] mijnCharArray = mijnVoornaam.ToCharArray();
mijnCharArray = mijnCharArray.Reverse();

instead of this:

string mijnVoornaam = "Remolino";
char[] mijnCharArray = mijnVoornaam.ToCharArray();
Array.Reverse(mijnCharArray);
like image 596
Remolino Avatar asked Oct 30 '14 16:10

Remolino


3 Answers

You can do both.

First it performed using LINQ, it creates a new sequence:

using System.Linq;

mijnCharArray = mijnCharArray.Reverse().ToArray();

Second makes changes in-place, is optimized and more efficient:

Array.Reverse(mijnCharArray);

Choice is yours, depends on your usage scenario.

like image 105
abatishchev Avatar answered Oct 20 '22 07:10

abatishchev


Because the first uses the LINQ extension method Reverse which returns an IEnumerable<char> instead of char[]. So you could do...

mijnCharArray = mijnCharArray.Reverse().ToArray();

but that would be less efficient than Array.Reverse since it has to create a new array and it doesn't know the final size beforehand.

like image 3
Tim Schmelter Avatar answered Oct 20 '22 07:10

Tim Schmelter


Actually; you can.

.Reverse is a LINQ extension method, and returns an IEnumerable<T> which is why the assignment fails. However, if you did this:

string mijnVoornaam = "Remolino";
char[] mijnCharArray = mijnVoornaam.ToCharArray();
mijnCharArray = mijnCharArray.Reverse().ToArray();

It would work just fine. Note that this returns a new array with the characters reversed.

Array.Reverse does an in-place reversal, and so returns void and you can't assign the result.

like image 3
BradleyDotNET Avatar answered Oct 20 '22 08:10

BradleyDotNET