Reputation: 5354
I have a function that takes an array as a parameter. The function then fills the array up with information of unknown length. So how would I create an array to store a message of unknown length? Because I can't specify the size of the array since I don't know the size of the message it is going to store.
Would this be valid?
byte [] array;
function (array);
And then the size of the array will be determined by the size of the message it is filled in? If this isn't possible how would I do this?
I need the array to be the exact size of the message it is filled up with, so I can't just specify the array to be some random size big enough to fit the message.
Additional, from a comment:
public int ReceiveFrom( byte[] buffer, int offset, int size,
SocketFlags socketFlags, ref EndPoint remoteEP )
Upvotes: 1
Views: 123
Reputation: 273854
About using
public int ReceiveFrom( byte[] buffer, int offset, int size,
SocketFlags socketFlags, ref EndPoint remoteEP )
You are supposed to use this in a loop. You are receiving parts of the total message (stream) at a time. Up to you to decide which part you need. Optionally shift the rest down and specify an offset
in the next call.
byte[] buffer = new byte[1024];
ínt n;
do
{
n = ReceiveFrom(buffer, 0, buffer.Lenght, ...);
if (n > 0)
// process n bytes in buffer
} while (n > 0);
Upvotes: 2
Reputation: 1703
You can use a List and then once your message is filled call ToArray
Edit
Example:
List<byte> message = new List<byte>();
message.Add(/*your byte*/);
//More Adds
function(message.ToArray());
Upvotes: 3
Reputation: 3399
It's hard to tell without knowing the exact details, but you could let the function create the array after it knows the length of the information.
Additionally, with Linq (using ToArray and ToList) you can cast from and to arrays and lists, but again, it's hard to tell without knowing the intentions.
Upvotes: 0
Reputation: 2241
Do you need to do something with the array before passing it to the function that fills it up? If you don't, why don't you just return the array from the function instead of passing it one:
byte[] retArray = function();
where function is:
byte[] function()
{
}
You can then find out the length of the array by checking:
if( retArray != null )
{
Console.WriteLine( retArray.Count );
}
Upvotes: 0