How can I pass byte array by reference to function?

Almunsaah 21 Reputation points
2022-10-05T11:11:51.967+00:00

Hi everybody,
I know arrays are passing by reference in c#, but in my case I get weird behavior.
byte[] b={} ;
if (getdata(b))
{
... Do something...
}
After calling getdata, b length is zero while inside getdata b has size more than zero.
I try using ref but nothing changes, any solution?
getdata body:
public bool getdata(byte[] data)
{
....
data=file.read(file.length);
returns true;
}
I know next mode is working perfectly but I don't need it :
public byte[] getdata()
{
....
byte[] data=file.read(file.length);
file.close();
returns data ;
}
Any help??
========================Updates=========================
Thank you for answer, to get a good answer for my question, I will ask it in different way:
How can I get byte array using function parameters(or arguments), I don't need using return value, I NEED ONLY using function parameters or arguments to get byte array.
public bool GetData(byte[] data)
{
data=.....;
return true;

}
.
.
.
byte[] data={}
if(GetData(data)|)
{
...
}
any help about this????!!!

Developer technologies C#
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-10-05T16:18:14.427+00:00

    you see to be missing basic concepts.

    there are two data types, value and reference.

    value types are immutable and copied on assignment:

    int i1 = 0;   
    int i2 = i1;  // i2 gets a copy of the i1 value   
    int i2 = 2;   // i2 get a  copy of 2, i1 still == 0   
       
    

    reference data types may or may not be immutable, but a variable has a reference to the data type:

    public class Foo { public string Bar; }   
       
    var f1 = new Foo { Bar = "hello" };   
    var f2 = f1;  // both f1 and f2 reference the same object   
    f1.Bar = "Bye";  // both f1.Bar and f2.Bar == "Bye"   
    

    now we get to methods. a method parameter variable may be passed by value (the default) or by reference. this is referring to the variable, not the data type.

    static void PassByValue (int i) { i = 2; }   
    static void PassByRef (ref int i) { i = 2; }   
       
    int i1 = 1;   
    PassByValue(i1);  // a copy of the variable is passed   
    Console.WriteLine(i1); // 1   
    PassByRef(ref i1);  // a reference to the variable is passed   
    Console.WriteLine(i1); // 2   
       
       
    

    an array is a reference type. when you pass it to a method, the method can modifiy elements in the array, but array do not support resizing. to change the size of an array, you must allocate a new one. if you want a method to change the size of an array, you must pass the array variable by ref, so the variable can be updated.

    static void GetBytes(ref byte[] bytes) { bytes = new byte[]{0,1}; }  
      
    byte[] bytes = new byte[]{};  
    GetBytes(ref bytes);  
    Console.WriteLine($"{bytes[0]},{bytes[1]}");  
      
    

    but a better approach is to have the method return a new array:

    static byte[] GetBytes() => new byte[] { 0,1 };  
      
    byte[] byes = GetBytes();  
    

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2022-10-05T13:01:50.653+00:00

    There are several issues with the test code. First, the code defines a zero length array. An array must be initialize with a length.

    Secondly, passing an array by ref passes a reference to a reference which can lead to hard to find bugs.

    Here's a better example.

    class Program  
    {  
        static void Main(string[] args)  
        {  
            ArrayTest();  
            //ListTest();  
        }  
      
        static void ListTest()  
        {  
            List<byte> buff = new List<byte>();  
            Printbuff(buff);  
      
            GetData(buff);  
            Printbuff(buff);  
        }  
      
      
        static void ArrayTest()  
        {  
            byte[] buff = new byte[5];  
            Printbuff(buff);  
      
            GetData(buff);  
            Printbuff(buff);  
        }  
        static void GetData(byte[] buff)  
        {  
            for(byte i = 0; i< buff.Length; i++)  
            {  
                buff[i] = i;  
            }  
        }  
      
        static void Printbuff(byte[] buff)  
        {  
            foreach(byte b in buff)  
            {  
                Console.WriteLine($"value: {b}");  
            }  
      
            Console.WriteLine($"--------------");  
        }  
      
      
        static void GetData(List<byte> buff)  
        {  
            for (byte i = 0; i < 5; i++)  
            {  
                buff.Add(i);  
            }  
        }  
      
        static void Printbuff(List<byte> buff)  
        {  
            foreach (byte b in buff)  
            {  
                Console.WriteLine($"value: {b}");  
            }  
      
            Console.WriteLine($"--------------");  
        }  
    }  
    

    If the array size is unknown at run time then use a generic List<byte> as shown above.

    Lastly, can you explain the actual use case rather than the solution.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.