N
N
Nonpacie2020-12-01 04:03:25
C++ / C#
Nonpacie, 2020-12-01 04:03:25

How to reverse a string with an extension method?

It is necessary to solve the problem of reversing an array of integers using the extension method, actually read about these methods and wrote a method that does not give errors and warnings, but also does not work, tell me, could there be a problem?

Program.cs

using System;

namespace Lab10
{
    internal static class Program
    {
        
        public static void Main(string[] args)
        {
            int[] array = new[] {1, 4, 5, 1, 3, 235, 634, 234, 12, 4, 3, 77, 141};
            array.PrintArray();

            array.ReverseArray();

            Console.WriteLine();
            foreach (var elem in array)
            {
                Console.Write($"{elem} _ ");
            }
        }
    }
}


Extension.cs
...
public static int[] ReverseArray(this int[] arr)
        {
            List<int> buffer = arr.ToList();
            buffer.Reverse();
            arr = buffer.ToArray();
            return arr;
        }
...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav, 2020-12-01
@Nonpacie

for (int i = 0; i < arr.Length / 2; i++)
{
   int tmp = arr[i];
   arr[i] = arr[arr.Length - i - 1];
   arr[arr.Length - i - 1] = tmp;
}

B
BasiC2k, 2020-12-01
@BasiC2k

I take it you have a study assignment?
If not, you can:
1. Convert array to List using .ToList
2. Run .Reverse command on List 3. Convert
List back to array with .ToArray command
Three lines of code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question