J.S.Orris
J.S.Orris

Reputation: 4841

Reverse an Array and assign to new array

Why do I get an error at the following when trying to initialize arrChar2 to the Reverse of arrChar1 (error is at line arrChar2 initialization)?:

char[] arrChar1 = inputString.ToCharArray();

char[] arrChar2 = arrChar1.Reverse();

Upvotes: 0

Views: 121

Answers (2)

Alex Herman
Alex Herman

Reputation: 2848

Probably the easiest way, as you don't need to create more variables:

using System;

 public class Program
 {
    public static void Main()
    {
        var inputString = "abcd";

        char[] arrChar1 = inputString.ToCharArray();

        Array.Reverse(arrChar1);

        Console.WriteLine(arrChar1);
    }
}

Upvotes: 1

Steve
Steve

Reputation: 216348

Because you are using the IEnumerable Reverse extensions that returns (in your context) an IEnumerable<char> not a char array.
If you want to get an array of chars, as output, you need to be explicit

char[] arrChar2 = arrChar1.Reverse().ToArray();

Upvotes: 4

Related Questions