Reputation: 309
I am using Marshal.SizeOf to know the size of my stucture:
struct loginStruct
{
public string userName;
public string password;
public loginStruct(string userName, string password)
{
this.userName = userName;
this.password = password;
}
}
Here is the use of this function:
int len = Marshal.SizeOf(typeof(loginStruct));
I got 2 programs. In one program len is equals to 8. In the other it equals to 16. It is the same struct. Why I got that differece?
Upvotes: 5
Views: 5126
Reputation: 113272
Methods don't affect the size given, so effectively we're talking about:
struct loginStruct
{
public string userName;
public string password;
}
That struct
has two reference type fields. As such, it has two fields in the memory which refer to objects on the heap, or to null
.
All reference type fields are 4 bytes in 32-bit .NET and 8 bytes in 64-bit .NET.
Hence the size would be 4 + 4 = 8 in 32-bit .NET or 8 + 8 = 16 in 64-bit .NET.
Upvotes: 5
Reputation: 17003
It is depending on the machine and on the build configuration. As @Joey said AnyCPU or 64-Bit
There are some tricks to avoid this problem:
For example you can check:
The application type Environment.Is64BitOperatingSystem
The size of IntPtr changes on 32 and 64
using System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32DeviceMgmt.SP_DEVINFO_DATA)
Upvotes: 1
Reputation: 354546
I'd guess one program is compiled for AnyCPU (which on a 64-bit platform will be 64-bit) and one for 32-bit.
Upvotes: 10