Fixed-length arrays as struct member

D

Dr. Len

Hi NG,
is it possible for struct to have a fixed-length array of primitive
types as member variable as in C++, such that the array doesn't need
to be allocated explicitly?

Eg.:
--------
public const int MAX_VALUES = 4;

public struct Weight
{
int indexes[MAX_VALUES];
float weights[MAX_VALUES];
}

Weight[] weights = new Weight[10];

// Access the array
for(int i = 0; i < MAX_VALUES; i++)
weights[0].indexes = -1;

--------
Rather than:

Weight[] weights = new Weight[10];

foreach(Weight w in weights)
w.indexes = new int[MAX_VALUES];
... and so on ...

// Access the array

The latter is very cumbersome method in my opinion.
 
M

Mattias Sjögren

In v2 you'll be able to write something like

unsafe struct Weight
{
fixed int indexes[MAX_VALUES];
fixed float weights[MAX_VALUES];
}

But since it only works with unsafe code enabled, I think it's rarely
worth using.



Mattias
 
D

Dr. Len

In v2 you'll be able to write something like

unsafe struct Weight
{
fixed int indexes[MAX_VALUES];
fixed float weights[MAX_VALUES];
}

But since it only works with unsafe code enabled, I think it's rarely
worth using.



Mattias

Actually, I need to use unsafe code in other places too, so it's not a
problem. Does v2 mean .NET Framework v1.1?
 
M

Mattias Sjögren

Actually, I need to use unsafe code in other places too, so it's not a
problem. Does v2 mean .NET Framework v1.1?

No, it means the upcoming v2.0. But it's just a syntactic shortcut for
the following, which you can write in current versions:

[StructLayout(LayoutKind.Auto, Size=4*4+4*4)]
unsafe struct Weight
{
public int GetIndex(int i)
{
fixed (Weight* pw = &this)
return ((int*)pw);
}

public void SetIndex(int i, int val)
{
fixed (Weight* pw = &this)
((int*)pw) = val;
}

public float GetWeight(int i)
{
fixed (Weight* pw = &this)
return ((float*)((byte*)pw + 16));
}

public void SetWeight(int i, float val)
{
fixed (Weight* pw = &this)
((float*)((byte*)pw + 16)) = val;
}
}



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top