Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamic byte array in c#

Status
Not open for further replies.

youssef

Programmer
Mar 13, 2001
96
0
0
BE
I looking how can I do for create a dynamic byte array.
and can add some byte by this function :

byte.Add(2);

best regards
 
Arrays are fixed size in .NET

But you can use an ArrayList collection that allows you to dynamically add/remove items.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Code:
ArrayList ar = new ArrayList();
byte b1=0x56;
byte b2=0xFF;
ar.Add(b1);
ar.Add(b2);
-obislavu-
 
I would to copy the value from my arraylist to an array byte.

An error appear :

An unhandled exception of type 'System.InvalidCastException' occurred in ArrayList1.exe

Additional information: Specified cast is not valid.

How can I do for resolving the problem ?

Best Regards

ArrayList XmdData = new ArrayList();
byte[] bXmdData = new byte[2];

XmdData.Add(0x02);
bXmdData[0] = (byte) XmdData[0];



 
The docs say to use the CopyTo method to copy the contents of an ArrayList to a vector (1-dimensional array).

[link ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfSystemCollectionsArrayListClassCopyToTopic1.htm]ms-help://MS.VSCC.2003/MS.MSDNQTR.2003FEB.1033/cpref/html/frlrfSystemCollectionsArrayListClassCopyToTopic1.htm[/url]

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
ArrayList.Add() add "object" type in the list and not numbers. This has to work:
Code:
ArrayList XmdData = new ArrayList();
byte[] bXmdData = new byte[2];
byte b1 =0x02;
XmdData.Add(b1);
bXmdData[0] = (byte)XmdData[0];
-obislavu-
 
Using obislavu's last comment as a solution, don't forget to call the method XmdData.TrimToSize() when you're done adding elements. That way the ArrayList count is 'trimmed' down to the number of elements you have added. Otherwise it will contain at least 64 null elements. Extra allocated memory drives me nuts. It's not required but I always use it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top