Reputation: 98810
From C# 5.0 in a Nutshell: The Definitive Reference in page 22;
Reference types require separate allocations of memory for the reference and object. The object consumes as many bytes as its fields, plus additional administrative overhead. The precise overhead is intrinsically private to the implementation of the .NET runtime, but at minimum the overhead is eight bytes, used to store a key to the object’s type, as well as temporary information such as its lock state for multithreading and a flag to indicate whether it has been fixed from movement by the garbage collector. Each reference to an object requires an extra four or eight bytes, depending on whether the .NET runtime is running on a 32- or 64-bit platform.
I'm not quite sure I understand this bold part completely. It says on 32-bit platforms a reference requires four bytes, on 64-bit platforms it requires eight bytes.
So, let's say we have
string s = "Soner";
How can I check how many bytes this s
reference requires?
Upvotes: 1
Views: 915
Reputation: 1502016
You can use Environment.Is64BitProcess
. If it is, every reference will be 8 bytes. If it's not, every reference will be 4 bytes. The type of the reference, and the contents of the object it refers to, are irrelevant.
EDIT: As noted in a now-deleted answer, IntPtr.Size
is even simpler.
EDIT: As noted in comments, although currently all references in a CLR are the same size, it's just possible that at some point it will go down a similar path to Hotspot, which uses "compressed oops" in many cases to store references as 32-bit values even in a 64-bit process (without limiting the memory available).
Upvotes: 6
Reputation: 22804
To expand on Jon Skeet's answer, to get the number of possible bytes you should do this:
int bytesInRef = Environment.Is64BitProcess ? 8 : 4;
However, this is an implementation detail. Not only should you not worry about this, you should ignore this. Here's a good blog post on (another) implementation detail, but it's still applicable as it talks about implementation details and how you shouldn't trust them or depend on them. Here: The Stack Is An Implementation Detail
Upvotes: 1
Reputation: 210583
If you really want to calculate the size of a reference, using this Reference.Size
should work:
using System;
using System.Reflection.Emit;
public static class Reference
{
public static readonly int Size = new Func<int>(delegate()
{
var method = new DynamicMethod(string.Empty, typeof(int), null);
var gen = method.GetILGenerator();
gen.Emit(OpCodes.Sizeof, typeof(object));
gen.Emit(OpCodes.Conv_I4);
gen.Emit(OpCodes.Ret);
return ((Func<int>)method.CreateDelegate(typeof(Func<int>)))();
})();
}
But going with the other answers is probably a better idea.
Upvotes: 2