'Try to do methods C#

I can try to do method for change length of array.

But newArray not visible in main...

What can i do for?

I am a begginer and need some help


    internal class Program
    {
        static int[] Addstart(ref int[] oldArray, int element)
        {
            int[] newArray = new int[oldArray.Length + 1];
            newArray[0] = element;
            for (int i = 1; i < newArray.Length; i++)
            {
                newArray[i] = oldArray[i - 1];
            }
            return newArray;

        static void Main(string[] args)
        {
            int[] oldArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
            
            Addstart(ref oldArray, 8);
            for(int i = 0; i < newArray.Length; i++)
                Console.WriteLine(newArray[i] + " ");

            Console.ReadKey();


        }
    }
}




Solution 1:[1]

When you want to use the ref approach to change the value of a variable on the caller side, you assign the new value inside the method Addstart() instead of using the return statement. The method can look like this:

static void Addstart(ref int[] oldArray, int element)
{
    int[] newArray = new int[oldArray.Length + 1];
    newArray[0] = element;
    for (int i = 1; i < newArray.Length; i++)
    {
        newArray[i] = oldArray[i - 1];
    }
    oldArray = newArray; // <-- set new value for ref parameter 'oldArray'
}

After that you call your Addstart() method and use the variable oldArray in your Main() method.

public static void Main(string[] args)
{
    int[] oldArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
     
    Addstart(ref oldArray, 8);
    for(int i = 0; i < oldArray.Length; i++)
        Console.WriteLine(oldArray[i] + " ");
}

This will generate the following output:

8 
1 
2 
3 
4 
5 
6 
7 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Progman