2

I am sitting through a very well-explained and thorough video tutorial series, using Visual Studio 2012 as my developing environment.

Anyway, one thing that is hard to figure out is this. Say you have this code

static void Main()
{
    int[] myArray = {0, 1, 2, 3};   
    Array.Reverse(myArray);   
    foreach (int item in myArray) Console.WriteLine(item);   
    Console.ReadLine();   
//console says 3,2,1,0
}

static void Main()
{     
    int[] myArray = {0, 1, 2, 3};   
    myArray.Reverse();   
    foreach (int item in myArray) Console.WriteLine(item);   
    Console.ReadLine();   
//console says 0, 1, 2, 3  
}

I'm not getting why using the base class's method permanently changes the order of the elements in the array from that point on, versus using the instance of the Array class (myArray) which only changes it for the current line, then it reverts back to the un-reversed order. Can anyone explain this?

9

In the first program, you called Array.Reverse, a static method of the Array class that reverses the array in-place.

In your second program, you called Enumerable.Reverse, an extension method that works on any kind of enumerable. As an array is a kind of enumerable, it does work on arrays. But it does not do in-place reversion, but instead returns a new enumerable that is the reverse of the one you passed in.

You could have done this:

static void Main()
{     
    int[] myArray = {0, 1, 2, 3};   
    var somethingThatCanBeUsedByforEachAndReturnsYourArrayReversed = myArray.Reverse();   
    foreach (int item in somethingThatCanBeUsedByforEachAndReturnsYourArrayReversed)
    {
       Console.WriteLine(item);   
    }
    Console.ReadLine();   
//console says 0, 1, 2, 3  
}

But to be honest, if you are still learning, leave your hands off of Enumerables and LinQ. They are great, but right now, way over your head. Simply deleting using System.Linq from your source file will make your life a lot easier while still learning.

  • 3
    While enumerables and extension methods created some confusion here, I wouldn't scare the OP with how difficult a concept they are so that he doesn't develop some sort of a complex ;) In and of themselves they're not a hard thing to grasp, the only problem is that the OP stumbled on them where it was unexpected – Konrad Morawski Jun 20 '15 at 12:32
  • Well, I can say when I was still just getting my head around List<string>, Dictionary<string, string>(), and how arrays could be Array, ArrayList, and string[], it took me a while before I got into Enumerable, IEnumerable, and Linq queries, which I consider more advanced. I think this post was dead-on, personally... 😀 – vapcguy Jun 21 '15 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.