In C# 1.x, when we declare an array, it is merely a reference (or pointer) that points to a sequence of elements. For example if we declare a structure like this:
struct Test { char[] letters; }
It will only take 4 bytes in memory because what it contains is a reference (or pointer) which is of int type. Several times with legacy code written in C/C++ programming language we need to pass data structures which accepts the fixed sized buffers and not only the pointer of the buffer. C# 2.0 provides this feature with its ‘fixed sized buffers’ declared with the keyword ‘fixed’
struct Test { fixed char letters[10]; }
Now the structure will take up 20 bytes (a Unicode character takes 2 bytes) in memory. But there are few important points and restrictions for using fixed sized buffers:
- Fixed sized buffers can only be contained in unsafe code
- They can only exist as instance members and not the local members of a method
- We must have to declare the size of the fixed sized buffer when we declare them. It is an error to write fixed char letters[]
- They can only be one dimensional. Multi-dimensional fixed sized buffers are not allowed