Hack Forums
[C#] Classes to read/write data to a series of bytes [CODE] - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] Classes to read/write data to a series of bytes [CODE] (/showthread.php?tid=1773244)



Classes to read/write data to a series of bytes [CODE] - Silicon - Sep 29, 2011

This is come code I've written and I use to read and write stuff to a byte array. This is very useful for transmitting data over sockets.
http://pastie.org/private/991hwnpj2gfmdi4bs6hxa
Enjoy! This is distrubuted under a simple license: Use it freely, include credits when distrubuted as source, free to modify as long as some credits are given.
(By credits, I mean a simple code comment)


* - scarfacekilla - Sep 29, 2011

why: DataWriter : IDisposable
if you dont dispose anything in the class ? :D

you could at least write:
PHP Code

<?php 
/// <summary>
  /// Dispose of this object, freeing up all used memory.
  /// </summary>
  
public void Dispose()
  {
     if(array==
null)return;
     array.
clear();
     array=
null;
  } 

yo could do:

PHP Code

<?php 
/// <summary>
  /// Adds the data onto the byte array, in T form.
  /// </summary>
  /// <param name="data">The data to add onto the array.</param>
  
public void Write<T>(T data)
  {
    if(
typeof(T)==typeof(string))
    array.
AddRange(ASCIIEncoding.Default.GetBytes(data));
    else
    array.
AddRange(BitConverter.GetBytes(data));
  } 


For your read i would rather use it more generic

PHP Code

<?php 
//pseudo code
 
public byte[] Read<T>()
{
List<
T> bytes = new List<T>();

for(var 
i = 0; i<sizeof(T);i++)
{
bytes.Add(_stream.ReadByte());
}
    return 
bytes.ToArray();
  } 

the reason is, you could send and read custom types and convert them, with your method you are stuck to what you provide and you have to extend the class all the time...


just suggestions - if i am wrong or you have different reasons feel free to express them and explain it to me :)



P.S. to send custom types/classes you need to restructure the code a bit more and use
BinaryFormatter / serialization blabla blupp .. google is our friend :)


* - Nonmod - Sep 30, 2011

PHP Code

<?php 
public override string ToString()
  {
    return 
ASCIIEncoding.Default.GetString(ToBytes());
  } 

Use UTF8, not ASCII.

EDIT:
PHP Code

<?php 
~DataReader()
  {
    
Dispose();
  } 

Not needed, CLR calls Dispose automatically on destruction.

P.S. Use destructors only as fallback mechanism, because you can't control when GC will do the cleanup for this object (if it ever does.)