#774 – Passing an Array as an out Parameter

Like other reference types, you can use an array as an output parameter, using the out keyword.  The out keyword indicates that you must assign a value to the array before returning from the method.  Also, within the method, you cannot reference the array parameter before you assign a new value to it.

        static int FindFibsThrough(int numFibs, out int[] fibs)
        {
            // Can't reference element of array
            //int i = fibs[0];

            // Can't assign to element of array
            //fibs[0] = 12;

            if (numFibs < 2)
                throw new Exception("Must return at least 2 numbers in sequence");

            // Must assign new value to array before we return
            fibs = new int[numFibs];

            fibs[0] = 0;
            fibs[1] = 1;
            int sum = 1;

            for (int i = 2; i < numFibs; i++)
            {
                fibs[i] = fibs[i - 1] + fibs[i - 2];
                sum += fibs[i];
            }

            return sum;
        }

You must also use the out keyword when calling the method.

            int[] myFibs;
            int sum = FindFibsThrough(10, out myFibs);

774-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #774 – Passing an Array as an out Parameter

  1. Rahul singh says:

    good articles

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: