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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With