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

I am new to programming. I learn C # through Bob Tabors video 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); 
+5
source share
5 answers

You can do both.

It was first executed using LINQ , it creates a new sequence:

 using System.Linq; mijnCharArray = mijnCharArray.Reverse().ToArray(); 

The second makes changes in place, optimized and more efficient:

 Array.Reverse(mijnCharArray); 

The choice is yours depending on your use case.

+4
source

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

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

but it will be less efficient than Array.Reverse , since it has to create a new array and it does not know the final size in advance.

+3
source

In fact; You can.

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

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

Everything will be fine. Note that this returns a new array with inverse characters.

Array.Reverse performs an in-place reversal and therefore returns void , and you cannot assign a result.

+3
source

You can actually do this if you use System.Linq , but this is an extension method for IEnumerable.

+1
source

You cannot use the Reverse extension method, since Reverse() returns an IEnumerable<char> , which is not a char[] . You must pass an IEnumerable<char> to the array. So this works, for example:

 char[] c = mijnVoornaam.Reverse().ToArray(); 

You can use Reverse in string too with this extension method:

 public static class ExtensionMethods { public static string Reverse(this string s) { return string.Concat(s.Reverse()); // or: // return new string(s.Reverse().ToArray()); } } 

Then just call:

 string reverse = "name".Reverse(); 
+1
source

Source: https://habr.com/ru/post/1205882/


All Articles