So you can use sizeof to get the size of a known built-in type in C# like
var size = sizeof(int);
But how do you get the size if you're in a situation like this?
var type = typeof(int);
var size = sizeof(type);
I checked stack overflow but the last question was fro 2013 and used something called Marshal.SizeOf which is now obsolete, and asking questions there just has people yelling at you for no reason.
Marshal.SizeOf is not obsolete, one overload was marked as obsolete but this was incorrect and it is no longer marked as such: https://github.com/dotnet/corefx/issues/8043
It's fine to use this for getting the size, but if the type contains any references to other objects the size will differ between 32 and 64 bit runtimes.
Thanks! So as long as they're built-in types, e.g. char, int, float, double, uint, I will not have any problems? I'm not planning to use custom types.
Those types should all have a fixed size: sizeof (C# Reference) | Microsoft Docs
Yes I know but if you have the type 'hidden' inside a variable, then you can either do an ugly switch case like:
if(foo.GetType() == typeof(int))
{
return sizeof(int);
}
if(foo.GetType() == typeof(float))
{
return sizeof(float);
}
Or, as far as I understand, use Marshal.SizeOf?
Yeah just pass it to SizeOf.
Sorry, you need to Log In to post a reply to this thread.