Hugo
OK This captures the essence of my problem (this is just an arbitrary test form project)
public partial class Form1 : Form
{
private unsafe struct structure
{
char data1;
long data2;
fixed byte data3[64];
}
public Form1()
{
InitializeComponent();
}
private unsafe void Form1_Load(object sender, EventArgs e)
{
int arg1;
decimal arg2;
structure arg3;
int size;
size = sizeof(structure); // what I can do now...
size = sizeof(decimal);
size = SizeFromType(typeof(structure)); // what I'd like to be able to do
size = SizeFromType(typeof(decimal));
}
public int SizeFromType (Type arg)
{
if (arg.IsValueType)
{
// How can I determine the size of the corresponding value type data
}
return (0);
}
}
Can you now see
The method 'SizeFromType' only has a Type, but sizeof NEEDS and only accepts an actual type name.
My guess here is that the validity of using "sizeof" is determined at compile time, not at runtime so I strongly suspect that the compiler replaces "sizeof(decimal)" with a hard numeric 8 !
It would have been great if the CTS had catered for this need, perhaps by having a field in Type called: ValueTypeSize that would simply be the very same value that the compiler sees/calculates when it compile "sizeof(...)".
So my question is am I correct Because my design is passing around Type args all over the place and there seems to be no way that I can get at the actual size (the value that sizeof would return).
This is OK if we are only going to have the predefined base types, a simple switch/case ladder with sizeof(byte), sizeof(char) etc etc can be coded. But when the user is passing around value type structures, there is no way for me to determine the size.
If anyone can suggest a way to calculate the size or use some equivalent of "sizeof" on a Type I will be most gratefu!
Thx
G