Nicholas,
However, the question has to be asked, why not just create a new array
when needed? If you are worried about memory concerns, that's what the GC
is for.
Well, I'm trying to make a method that is called a lot more efficient. I
came up with three version:
Version 1:
public static void StringToFixedSizeByteArray(string sValue, byte[]
buffer)
{
if (buffer != null)
{
if ((sValue != null) && (sValue.Length > 0))
{
for(int i = 0; i < buffer.Length; i++)
{
if (i < sValue.Length)
buffer[i] = (byte) sValue[i];
else buffer[i] = 0;
}
}
else
{
Array.Clear(buffer, 0, buffer.Length);
// for(int i = 0; i < buffer.Length; i++)
// buffer[i] = 0;
}
}
}
and finally:
Version 2:
public static byte[] StringToFixedSizeByteArray(string sValue, int
iFixedSize)
{
byte[] buffer;
if (iFixedSize > 0)
{
buffer = new byte[iFixedSize];
if ((sValue != null) && (sValue.Length > 0))
{
if (sValue.Length < iFixedSize)
System.Text.Encoding.UTF8.GetBytes(
sValue, 0, sValue.Length, buffer, 0);
else System.Text.Encoding.UTF8.GetBytes(
sValue, 0, iFixedSize, buffer, 0);
}
}
else buffer = null;
return buffer;
}
Version 3:
public static byte[] StringToFixedSizeByteArray(string sValue, int
iFixedSize)
{
byte[] buffer;
if (iFixedSize > 0)
{
buffer = new byte[iFixedSize];
if ((sValue != null) && (sValue.Length > 0))
{
for(int i = 0; i < buffer.Length; i++)
{
if (i < sValue.Length)
buffer[i] = (byte) sValue[i];
else break;
}
}
}
else buffer = null;
return buffer;
}
Version 3 is the fastest; however, I think I'm going to go with Version 2.
Dave