array question

  • Thread starter Thread starter Horatiu Ripa
  • Start date Start date
H

Horatiu Ripa

I'm having one or more classes that contains only declarations of primitives and primitives initialized arrays
i.e:
class PrimitivesStructure
{
public int32 integer1;
public char[] array1 = new char[20];
public int[] array2 = new int[10];
...
}
How can I found, dianmically, from another class, the length in bytes of declared primitives arrays?
For primitive fields it's simple:

PrimitivesStructure myObject = new PrimitivesStructure();
foreach (System.Reflection.FieldInfo fi in myObject.GetType().GetFields())
{
if (!fi.FieldType.IsArray)
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(Activator..CreateInstance(fi.FieldType)));
}
 
Horatiu,

Technically, what you are doing isn't correct. When you use the static
SizeOf method on the Marshal class, it is the size of the marshaled data,
not of the representation in .NET. Granted, there usually is a one-to-one
relationship between the number of bytes used to represent the type in .NET
and in the unmanaged realm, but in general, it should not be assumed that is
the case.

What you could do is use the sizeof operator, but that is only allowed
in unsafe code. If that is not acceptable, then you should create a method
which will map the types to their sizes.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- nick(dot)paldino=at=exisconsulting<dot>com

I'm having one or more classes that contains only declarations of primitives
and primitives initialized arrays
i.e:
class PrimitivesStructure
{
public int32 integer1;
public char[] array1 = new char[20];
public int[] array2 = new int[10];
...
}
How can I found, dianmically, from another class, the length in bytes of
declared primitives arrays?
For primitive fields it's simple:

PrimitivesStructure myObject = new PrimitivesStructure();
foreach (System.Reflection.FieldInfo fi in myObject.GetType().GetFields())
{
if (!fi.FieldType.IsArray)

Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(Activator.Cr
eateInstance(fi.FieldType)));
}
 

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

Back
Top