Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a byte array member for a structure in C#

Tags:

c#

structure

I have a structure definition as follows:

public struct check
{
    public int[] x = new int[3]; //error
}

This is an error because you cant define an array size for a structure member in C#. I cant define the space for this array even in a default constructor in C# because parameterless constructors aren't allowed.

How do I do it? I know structures are immutable in C#.

I am using this structure not to create new objects but just to typecast objects of other class types.

check corp = (check )WmUtils.WM_GetObj(Attr);

Wm_getObj returns an object of check2 class type. Is readonly keyword helpful here?

like image 813
Tyler Durden Avatar asked Jun 28 '26 16:06

Tyler Durden


2 Answers

You can't have a parameter less constructor and you can't define an array with size in struct, this leaves you with a structure constructor taking a size as parameter like:

public struct check
{
    public int[] x;
    public check(int size)
    {
        x = new int[size];
    }
}
like image 117
Habib Avatar answered Jul 01 '26 06:07

Habib


How about a fixed array buffer:

public unsafe struct Buffer
{
    const int Size=100;
    fixed byte data[Size];

    public void Clear()
    {
        fixed(byte* ptr=data)
        {
            // Fill values with 0
            for(int i=0; i<Size; i++)
            {
                ptr[i]=0;
            }
        }
    }

    public void Store(byte[] array, int index)
    {
        fixed(byte* ptr=data)
        {
            // find max elements remaining
            int N=Math.Min(index + array.Length, Size) - index;
            // Fill values from input bytes
            for(int i=0; i<N; i++)
            {
                ptr[index+i]=array[i];
            }
        }
    }

    public byte[] ToArray()
    {
        byte[] array=new byte[Size];
        fixed(byte* ptr=data)
        {
            // Extract all data
            for(int i=0; i<Size; i++)
            {
                array[i]=ptr[i];
            }
        }
        return array;
    }
}

unsafe class Program
{
    static void Main(string[] args)
    {
        Buffer buffer=new Buffer();
        // buffer contains 100 bytes
        int size=sizeof(Buffer);
        // size = 100
        buffer.Clear();
        // data = { 0, 0, 0, ... }
        buffer.Store(new byte[] { 128, 207, 16, 34 }, 0);

        byte[] data=buffer.ToArray();
        // { 128, 207, 16, 34, 0, 0, ... }
    }
}

(PS need to compile with allow unsafe code)

like image 45
John Alexiou Avatar answered Jul 01 '26 05:07

John Alexiou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!