0

Other methods like Array.Sort() don't use ref and yet they change the array.

Also this code confuses me:

using System.Linq;
using System;

namespace jmennyprostor {
    public static void Main(string[] args)
    {
        int[] mojepole = {4,4,5,2,4};
        pole.changearray(mojepole); // this does change mojepole
        pole.resizearray(mojepole); // this magically does not change mojepole
        pole.resizearrayworking(ref mojepole); // this DOES change mojepole
    }

    public class pole 
    {
        public static void changearray(int[] polerole)
        {
            polerole[2] = 44444;
        }

        public static void resizearray(int[] polerole)
        {
            Array.Resize(polerole);
        }

        public static void resizearrayworking(ref int[] polerole)
        {
            Array.Resize(polerole);
        }
    }
}
2

1 Answer 1

2

Because the array may not actually be resized. So you pass in a reference to an array of size N, and the method may allocate a new array of size newSize and change your reference to point to the new array.

It has a similar effect as

oldArray = Array.Resize(oldArray, newSize);

if the method returned a reference to the new array instead of using a ref argument.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.