I am "optimizing" the code of some interpreter that I am doing and for this I need to know the size in bytes of my class Token
, which is made up of two variables: Type (enum)
, Value (object)
and an override of the method ToString()
:
enum TokenType { String, Keyword, Ident, Number, Symbol }
class Token
{
TokenType Type;
object Value;
public override string ToString() { return "Type: " + Type.ToString() + "\t\tValue: " + Value.ToString(); }
}
When I use a class for definition, it doesn't allow me to do sizeof
in said class, however, when I define Token
as a struct
:
struct Token
{
TokenType Type;
object Value;
public override string ToString() { return "Type: " + Type.ToString() + "\t\tValue: " + Value.ToString(); }
}
The sizeof
default function doesn't let me know the size, so I managed struct
to get it to give me the result:
Console.WriteLine(Marshal.SizeOf(typeof(Token))); // Resultado: 16
I have read some answers from SO but I still have the same question about this function, why can't sizeof
de System.Runtime.InteropServices
or the original function be used in a class, but in a struct
?
I don't have much experience with c# but maybe this is what you are looking for, if asking why I can't get the value you want some alternative:
Test
https://msdn.microsoft.com/es-es/library/5s4920fa(v=vs.100).aspx
https://msdn.microsoft.com/es-es/library/system.runtime.interopservices.structlayoutattribute(v=vs.110).aspx
The Marshal.SizeOf() documentation says (emphasis mine ):
But what is an unmanaged type ? The C# 3.5 specification says, in section 18.2 - Pointer types:
With the above, it could be concluded that:
Marshal.SizeOf(typeof(T))
, beingT
a struct containing a String field should failMarshal.SizeOf(typeof(T))
, beingT
an enumerator it should workWhen executing the code we see that the opposite happens, why? The C# compiler by default decorates structures with the StructLayout attribute and the Sequential layout value as the documentation says . And what about the Enums? Well , it seems that it treats them with LayoutKind.Auto
With this information, and seeing what (I think) you want to do, I would say that this is not the solution to your problem and you could better use a profiler.