What’s the best way of returning an array from a method?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: What’s the best way of returning an array from a method?

  1. #1

    Resolved What’s the best way of returning an array from a method?

    In plain C, I would do this:
    Code:
    void GetArray(
        mytype* pBuff   // [out] Pointer to the buffer in which array is returned to the calling code.
        int iBuffLen);  // [in]  Length of the buffer
    {
        for (i = 0; i < iBufflen; ++i) pBuff[i] = something;
    }
    Array is allocate once and never copied, unless I explicitly call for that.

    In C#, it's possible to return array from a method:
    Code:
    private byte [] GetArray()
    {
        byte[] iRet = {1,2,3,4,5};
        // ...
        return iRet;
    }
    Is this efficient? Is this good practice? Do C# methods always copy the local array when it's returned? Are there any other pitfalls?

    I found this article, which warns about pitfalls of using arrays with properties. At the same time, it doesn't talk about returning arrays from methods.

    Any suggestions references and insight are appreciated!

    Cheers,
    - Nick
    Last edited by kender_a; November 29th, 2010 at 01:09 AM. Reason: resolved

  2. #2
    Join Date
    Aug 2008
    Posts
    902

    Re: What’s the best way of returning an array from a method?

    Comparing C to C# is apples to oranges. Ultimately, you don't have the type of control you used to have in C.

    You should first read up on the difference between value types and reference types. Unlike in C++, there is a big difference between a class and a struct.

    In your example:

    Code:
    private byte [] GetArray()
    {
        byte[] iRet = {1,2,3,4,5};
        // ...
        return iRet;
    }
    iRet is a reference type, so GetArray only returns an object that references the array data, which exists in heap memory, not on the stack.


    Code:
    byte[] Array1 = {1,2,3,4,5};
    byte[] Array2 = Array1; // Array2 and Array1 share the same data
    byte[] Array3 = (byte[])Array1.Clone(); // Array3 gets it's own separate data
    This is the only way to deal with arrays in C#. Also, you should probably check out List<> from collections, which is a bit like a vector in C++, it's better to use that then an array most of the time. List<> is a reference type, just like an array, but it supports dynamic size adjustments.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center