
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Declaring a Fixed-Size Structure with an Embedded Array
|
1081
Solution
Use a fixed array inside of a structure:
public unsafe struct UnsafeByteArray
{
public fixed byte Data[254];
}
Discussion
A fixed type can be one of the following built-in types: bool, byte, sbyte, char, short,
ushort, int, uint, long, ulong, float,ordouble. In addition, the array must be a fixed
size. For example, the following code will not compile:
public unsafe struct UnsafeByteArray
{
public fixed byte Data1[]; // Needs to be a fixed size.
public fixed byte[] Data2; // Needs to be one of the
// aforementioned built-in types.
}
A fixed-size buffer has a few other limitations, including:
• You can use it only in an unsafe context.
• You cannot declare it as a
static field, only as an instance field.
• It can be only a one-dimensional array with a lower bound of zero (i.e., a vector
array).
Declaring a structure with an embedded array in the following manner:
public struct SafeByteArray
{
public SafeByteArray(int size)
{
// Create the byte array.
Data = new byte[254];
}
public byte[] Data;
}
simply creates a structure that is 8 bytes in size. This is because arrays are reference
types and are created on the managed heap while the structure,
SafeByteArray, is cre-
ated on the stack with a 4-byte pointer to the array on the ...