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
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.