Re: How can I pass a multidimensional array as a ref parameter in func

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Arrays are always passed by reference even if you omit 'ref' before the
argument. Array's name is its address.

"Jon Skeet [C# MVP]" <skeet@xxxxxxxxx> wrote in message
news:MPG.1d4b7e71907c4c8d98c4f5@xxxxxxxxxxxxxxxxxxxxxxx
vmsgman <vmsgman@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
> Here is a code sample ...
>
> int blah = ReadFile( defArray[,], defFileName, w, h);
>
> // Read File Contents into memory array and return for processing
> public int ReadFile( ref ushort[,] nArray, string sFname, int w, int h)
> {
> FileStream fs = new FileStream(sFname, FileMode.Open, FileAccess.Read);
> BinaryReader br = new BinaryReader(fs);
> // Read data
> for (int y=0; y<h; y++)
> {
> for (int x=0; x<w; x++)
> {
> nArray[x,y] = br.ReadUInt16();
> }
> }
> br.Close();
> fs.Close();
> return 0;
> }
>
> Can anyone help get this to work and compile ???

You pass arrays by reference in exactly the same way as you pass
anything else by reference:

int blah = ReadFile (ref defArray, defFileName, w, h);

However, it seems to me that it would be more appropriate as a return
value in the above - it's the result of reading the file, and currently
you're just returning 0. If that's meant to be a status code, you
should consider using exceptions for indicating errors.

You should also use "using" blocks (or their equivalent, try/finally
blocks) to make sure that files get closed whether or not an exception
is thrown.

--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


.



Relevant Pages

  • Re: <Help> Simple Pause Needed.
    ... before arrays, since arrays are error-prone, but I suppose your ... void f(int a, int b); ... It does not matter whether you pass by reference or by value. ... cin>> continue; ...
    (comp.lang.cpp)
  • Re: textbook authors: passing by ref is NOT more efficient!
    ... efficiency in terms of performance and we are talking reference objects. ... classic example (using int values, ... Console.WriteLine("Value after by ref routine ", ... reference to the array object even if you don't say "ref", ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: c file reading
    ... Robert Gamble wrote: ... variables or arrays) please? ... int main { ... serve you well to pick up a good reference on C programming, ...
    (comp.lang.c)
  • Re: Parameters byref
    ... I know that objects can be passed by reference and updated in a function. ... Those modifiers are 'out' and 'ref'. ... private void MyRefMethod (ref int a, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: c file reading
    ... variables or arrays) please? ... int main { ... Robert Gamble ... serve you well to pick up a good reference on C programming, ...
    (comp.lang.c)