-5

I have a few questions regarding arrays in C#.

  1. In a Method we can have one return value. Can we return an array?
  2. If returning an array is not possible, how we can use the array collected in that method and use in a calling method?

Below is my code.

public ArtWorkData[,] getExcelFile(int sheetNumber)
    {
        string[,] excRecord = new string[rowCount, colCount];
        excRecord[0, 0] = { {"TOPRIGHT", "TOPLEFT"},
                            {"MIDRIGHT", "MIDLEFT},
                            {"BOTRIGHT", "BOTLEFT"} }

        return excRecord;
     }

I want to know the logic of it and how we can pass the array out of the method. Thank you guys.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
NerdyLuke
  • 1
  • 3

1 Answers1

0

An array is a reference type, so you can return a reference to it just like any reference type. Arrays also implement the IEnumerable generic interface, so you can also cast it to that if it makes you feel better.

For example:

public int[] GetNumbers()
{
    int[] numbers = new int[5];
    numbers[0]=34;
    return numbers;
}

public void DoStuff()
{
    IEnumerable<int> data = GetNumbers();
    ...

}

Returning a reference to a reference type does not copy the object - it copies a reference to it. The function that you return the array reference to can change the contents of the original array!

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
  • Robert, thanks for that clue. I noticed my error. Now is to copy the array. Any clue how to do that? – NerdyLuke Sep 04 '17 at 02:46
  • @NerdyLuke sure, look [here](https://stackoverflow.com/questions/14651899/create-a-copy-of-integer-array). – Robert Columbia Sep 04 '17 at 02:51
  • Robert, it's really cool. I got it to work already. Next step is to use the data in all the array. Some planning needed. Will post, if I faced with the more problems. Cheers mate. – NerdyLuke Sep 04 '17 at 03:54